12cab237bSDimitry Andric //===- SafeStack.cpp - Safe Stack Insertion -------------------------------===//
23ca95b02SDimitry Andric //
33ca95b02SDimitry Andric // The LLVM Compiler Infrastructure
43ca95b02SDimitry Andric //
53ca95b02SDimitry Andric // This file is distributed under the University of Illinois Open Source
63ca95b02SDimitry Andric // License. See LICENSE.TXT for details.
73ca95b02SDimitry Andric //
83ca95b02SDimitry Andric //===----------------------------------------------------------------------===//
93ca95b02SDimitry Andric //
103ca95b02SDimitry Andric // This pass splits the stack into the safe stack (kept as-is for LLVM backend)
113ca95b02SDimitry Andric // and the unsafe stack (explicitly allocated and managed through the runtime
123ca95b02SDimitry Andric // support library).
133ca95b02SDimitry Andric //
143ca95b02SDimitry Andric // http://clang.llvm.org/docs/SafeStack.html
153ca95b02SDimitry Andric //
163ca95b02SDimitry Andric //===----------------------------------------------------------------------===//
173ca95b02SDimitry Andric
183ca95b02SDimitry Andric #include "SafeStackColoring.h"
193ca95b02SDimitry Andric #include "SafeStackLayout.h"
202cab237bSDimitry Andric #include "llvm/ADT/APInt.h"
212cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
222cab237bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
232cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
243ca95b02SDimitry Andric #include "llvm/ADT/Statistic.h"
255517e702SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
263ca95b02SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
274ba319b5SDimitry Andric #include "llvm/Analysis/InlineCost.h"
282cab237bSDimitry Andric #include "llvm/Analysis/LoopInfo.h"
293ca95b02SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
303ca95b02SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
312cab237bSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
324ba319b5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
332cab237bSDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
34d8866befSDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
352cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
362cab237bSDimitry Andric #include "llvm/IR/Argument.h"
372cab237bSDimitry Andric #include "llvm/IR/Attributes.h"
382cab237bSDimitry Andric #include "llvm/IR/CallSite.h"
392cab237bSDimitry Andric #include "llvm/IR/ConstantRange.h"
403ca95b02SDimitry Andric #include "llvm/IR/Constants.h"
413ca95b02SDimitry Andric #include "llvm/IR/DIBuilder.h"
423ca95b02SDimitry Andric #include "llvm/IR/DataLayout.h"
433ca95b02SDimitry Andric #include "llvm/IR/DerivedTypes.h"
442cab237bSDimitry Andric #include "llvm/IR/Dominators.h"
453ca95b02SDimitry Andric #include "llvm/IR/Function.h"
463ca95b02SDimitry Andric #include "llvm/IR/IRBuilder.h"
473ca95b02SDimitry Andric #include "llvm/IR/InstIterator.h"
482cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
493ca95b02SDimitry Andric #include "llvm/IR/Instructions.h"
503ca95b02SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
513ca95b02SDimitry Andric #include "llvm/IR/Intrinsics.h"
523ca95b02SDimitry Andric #include "llvm/IR/MDBuilder.h"
533ca95b02SDimitry Andric #include "llvm/IR/Module.h"
542cab237bSDimitry Andric #include "llvm/IR/Type.h"
552cab237bSDimitry Andric #include "llvm/IR/Use.h"
562cab237bSDimitry Andric #include "llvm/IR/User.h"
572cab237bSDimitry Andric #include "llvm/IR/Value.h"
583ca95b02SDimitry Andric #include "llvm/Pass.h"
592cab237bSDimitry Andric #include "llvm/Support/Casting.h"
603ca95b02SDimitry Andric #include "llvm/Support/Debug.h"
612cab237bSDimitry Andric #include "llvm/Support/ErrorHandling.h"
623ca95b02SDimitry Andric #include "llvm/Support/MathExtras.h"
632cab237bSDimitry Andric #include "llvm/Support/raw_ostream.h"
642cab237bSDimitry Andric #include "llvm/Target/TargetMachine.h"
653ca95b02SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
664ba319b5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
672cab237bSDimitry Andric #include <algorithm>
682cab237bSDimitry Andric #include <cassert>
692cab237bSDimitry Andric #include <cstdint>
702cab237bSDimitry Andric #include <string>
712cab237bSDimitry Andric #include <utility>
723ca95b02SDimitry Andric
733ca95b02SDimitry Andric using namespace llvm;
743ca95b02SDimitry Andric using namespace llvm::safestack;
753ca95b02SDimitry Andric
76302affcbSDimitry Andric #define DEBUG_TYPE "safe-stack"
773ca95b02SDimitry Andric
783ca95b02SDimitry Andric namespace llvm {
793ca95b02SDimitry Andric
803ca95b02SDimitry Andric STATISTIC(NumFunctions, "Total number of functions");
813ca95b02SDimitry Andric STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
823ca95b02SDimitry Andric STATISTIC(NumUnsafeStackRestorePointsFunctions,
833ca95b02SDimitry Andric "Number of functions that use setjmp or exceptions");
843ca95b02SDimitry Andric
853ca95b02SDimitry Andric STATISTIC(NumAllocas, "Total number of allocas");
863ca95b02SDimitry Andric STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
873ca95b02SDimitry Andric STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
883ca95b02SDimitry Andric STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
893ca95b02SDimitry Andric STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
903ca95b02SDimitry Andric
913ca95b02SDimitry Andric } // namespace llvm
923ca95b02SDimitry Andric
934ba319b5SDimitry Andric /// Use __safestack_pointer_address even if the platform has a faster way of
944ba319b5SDimitry Andric /// access safe stack pointer.
954ba319b5SDimitry Andric static cl::opt<bool>
964ba319b5SDimitry Andric SafeStackUsePointerAddress("safestack-use-pointer-address",
974ba319b5SDimitry Andric cl::init(false), cl::Hidden);
984ba319b5SDimitry Andric
994ba319b5SDimitry Andric
1003ca95b02SDimitry Andric namespace {
1013ca95b02SDimitry Andric
1023ca95b02SDimitry Andric /// Rewrite an SCEV expression for a memory access address to an expression that
1033ca95b02SDimitry Andric /// represents offset from the given alloca.
1043ca95b02SDimitry Andric ///
1053ca95b02SDimitry Andric /// The implementation simply replaces all mentions of the alloca with zero.
1063ca95b02SDimitry Andric class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
1073ca95b02SDimitry Andric const Value *AllocaPtr;
1083ca95b02SDimitry Andric
1093ca95b02SDimitry Andric public:
AllocaOffsetRewriter(ScalarEvolution & SE,const Value * AllocaPtr)1103ca95b02SDimitry Andric AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
1113ca95b02SDimitry Andric : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
1123ca95b02SDimitry Andric
visitUnknown(const SCEVUnknown * Expr)1133ca95b02SDimitry Andric const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1143ca95b02SDimitry Andric if (Expr->getValue() == AllocaPtr)
1153ca95b02SDimitry Andric return SE.getZero(Expr->getType());
1163ca95b02SDimitry Andric return Expr;
1173ca95b02SDimitry Andric }
1183ca95b02SDimitry Andric };
1193ca95b02SDimitry Andric
1203ca95b02SDimitry Andric /// The SafeStack pass splits the stack of each function into the safe
1213ca95b02SDimitry Andric /// stack, which is only accessed through memory safe dereferences (as
1223ca95b02SDimitry Andric /// determined statically), and the unsafe stack, which contains all
1233ca95b02SDimitry Andric /// local variables that are accessed in ways that we can't prove to
1243ca95b02SDimitry Andric /// be safe.
1255517e702SDimitry Andric class SafeStack {
1265517e702SDimitry Andric Function &F;
1275517e702SDimitry Andric const TargetLoweringBase &TL;
1285517e702SDimitry Andric const DataLayout &DL;
1295517e702SDimitry Andric ScalarEvolution &SE;
1303ca95b02SDimitry Andric
1313ca95b02SDimitry Andric Type *StackPtrTy;
1323ca95b02SDimitry Andric Type *IntPtrTy;
1333ca95b02SDimitry Andric Type *Int32Ty;
1343ca95b02SDimitry Andric Type *Int8Ty;
1353ca95b02SDimitry Andric
1363ca95b02SDimitry Andric Value *UnsafeStackPtr = nullptr;
1373ca95b02SDimitry Andric
1383ca95b02SDimitry Andric /// Unsafe stack alignment. Each stack frame must ensure that the stack is
1393ca95b02SDimitry Andric /// aligned to this value. We need to re-align the unsafe stack if the
1403ca95b02SDimitry Andric /// alignment of any object on the stack exceeds this value.
1413ca95b02SDimitry Andric ///
1423ca95b02SDimitry Andric /// 16 seems like a reasonable upper bound on the alignment of objects that we
1433ca95b02SDimitry Andric /// might expect to appear on the stack on most common targets.
1443ca95b02SDimitry Andric enum { StackAlignment = 16 };
1453ca95b02SDimitry Andric
1464ba319b5SDimitry Andric /// Return the value of the stack canary.
1473ca95b02SDimitry Andric Value *getStackGuard(IRBuilder<> &IRB, Function &F);
1483ca95b02SDimitry Andric
1494ba319b5SDimitry Andric /// Load stack guard from the frame and check if it has changed.
1503ca95b02SDimitry Andric void checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
1513ca95b02SDimitry Andric AllocaInst *StackGuardSlot, Value *StackGuard);
1523ca95b02SDimitry Andric
1534ba319b5SDimitry Andric /// Find all static allocas, dynamic allocas, return instructions and
1543ca95b02SDimitry Andric /// stack restore points (exception unwind blocks and setjmp calls) in the
1553ca95b02SDimitry Andric /// given function and append them to the respective vectors.
1563ca95b02SDimitry Andric void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
1573ca95b02SDimitry Andric SmallVectorImpl<AllocaInst *> &DynamicAllocas,
1583ca95b02SDimitry Andric SmallVectorImpl<Argument *> &ByValArguments,
1593ca95b02SDimitry Andric SmallVectorImpl<ReturnInst *> &Returns,
1603ca95b02SDimitry Andric SmallVectorImpl<Instruction *> &StackRestorePoints);
1613ca95b02SDimitry Andric
1624ba319b5SDimitry Andric /// Calculate the allocation size of a given alloca. Returns 0 if the
1633ca95b02SDimitry Andric /// size can not be statically determined.
1643ca95b02SDimitry Andric uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
1653ca95b02SDimitry Andric
1664ba319b5SDimitry Andric /// Allocate space for all static allocas in \p StaticAllocas,
1673ca95b02SDimitry Andric /// replace allocas with pointers into the unsafe stack and generate code to
1683ca95b02SDimitry Andric /// restore the stack pointer before all return instructions in \p Returns.
1693ca95b02SDimitry Andric ///
1703ca95b02SDimitry Andric /// \returns A pointer to the top of the unsafe stack after all unsafe static
1713ca95b02SDimitry Andric /// allocas are allocated.
1723ca95b02SDimitry Andric Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
1733ca95b02SDimitry Andric ArrayRef<AllocaInst *> StaticAllocas,
1743ca95b02SDimitry Andric ArrayRef<Argument *> ByValArguments,
1753ca95b02SDimitry Andric ArrayRef<ReturnInst *> Returns,
1763ca95b02SDimitry Andric Instruction *BasePointer,
1773ca95b02SDimitry Andric AllocaInst *StackGuardSlot);
1783ca95b02SDimitry Andric
1794ba319b5SDimitry Andric /// Generate code to restore the stack after all stack restore points
1803ca95b02SDimitry Andric /// in \p StackRestorePoints.
1813ca95b02SDimitry Andric ///
1823ca95b02SDimitry Andric /// \returns A local variable in which to maintain the dynamic top of the
1833ca95b02SDimitry Andric /// unsafe stack if needed.
1843ca95b02SDimitry Andric AllocaInst *
1853ca95b02SDimitry Andric createStackRestorePoints(IRBuilder<> &IRB, Function &F,
1863ca95b02SDimitry Andric ArrayRef<Instruction *> StackRestorePoints,
1873ca95b02SDimitry Andric Value *StaticTop, bool NeedDynamicTop);
1883ca95b02SDimitry Andric
1894ba319b5SDimitry Andric /// Replace all allocas in \p DynamicAllocas with code to allocate
1903ca95b02SDimitry Andric /// space dynamically on the unsafe stack and store the dynamic unsafe stack
1913ca95b02SDimitry Andric /// top to \p DynamicTop if non-null.
1923ca95b02SDimitry Andric void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
1933ca95b02SDimitry Andric AllocaInst *DynamicTop,
1943ca95b02SDimitry Andric ArrayRef<AllocaInst *> DynamicAllocas);
1953ca95b02SDimitry Andric
1963ca95b02SDimitry Andric bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
1973ca95b02SDimitry Andric
1983ca95b02SDimitry Andric bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
1993ca95b02SDimitry Andric const Value *AllocaPtr, uint64_t AllocaSize);
2003ca95b02SDimitry Andric bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
2013ca95b02SDimitry Andric uint64_t AllocaSize);
2023ca95b02SDimitry Andric
2034ba319b5SDimitry Andric bool ShouldInlinePointerAddress(CallSite &CS);
2044ba319b5SDimitry Andric void TryInlinePointerAddress();
2054ba319b5SDimitry Andric
2063ca95b02SDimitry Andric public:
SafeStack(Function & F,const TargetLoweringBase & TL,const DataLayout & DL,ScalarEvolution & SE)2075517e702SDimitry Andric SafeStack(Function &F, const TargetLoweringBase &TL, const DataLayout &DL,
2085517e702SDimitry Andric ScalarEvolution &SE)
2095517e702SDimitry Andric : F(F), TL(TL), DL(DL), SE(SE),
2105517e702SDimitry Andric StackPtrTy(Type::getInt8PtrTy(F.getContext())),
2115517e702SDimitry Andric IntPtrTy(DL.getIntPtrType(F.getContext())),
2125517e702SDimitry Andric Int32Ty(Type::getInt32Ty(F.getContext())),
2135517e702SDimitry Andric Int8Ty(Type::getInt8Ty(F.getContext())) {}
2143ca95b02SDimitry Andric
2155517e702SDimitry Andric // Run the transformation on the associated function.
2165517e702SDimitry Andric // Returns whether the function was changed.
2175517e702SDimitry Andric bool run();
2185517e702SDimitry Andric };
2193ca95b02SDimitry Andric
getStaticAllocaAllocationSize(const AllocaInst * AI)2203ca95b02SDimitry Andric uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) {
2215517e702SDimitry Andric uint64_t Size = DL.getTypeAllocSize(AI->getAllocatedType());
2223ca95b02SDimitry Andric if (AI->isArrayAllocation()) {
2233ca95b02SDimitry Andric auto C = dyn_cast<ConstantInt>(AI->getArraySize());
2243ca95b02SDimitry Andric if (!C)
2253ca95b02SDimitry Andric return 0;
2263ca95b02SDimitry Andric Size *= C->getZExtValue();
2273ca95b02SDimitry Andric }
2283ca95b02SDimitry Andric return Size;
2293ca95b02SDimitry Andric }
2303ca95b02SDimitry Andric
IsAccessSafe(Value * Addr,uint64_t AccessSize,const Value * AllocaPtr,uint64_t AllocaSize)2313ca95b02SDimitry Andric bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize,
2323ca95b02SDimitry Andric const Value *AllocaPtr, uint64_t AllocaSize) {
2335517e702SDimitry Andric AllocaOffsetRewriter Rewriter(SE, AllocaPtr);
2345517e702SDimitry Andric const SCEV *Expr = Rewriter.visit(SE.getSCEV(Addr));
2353ca95b02SDimitry Andric
2365517e702SDimitry Andric uint64_t BitWidth = SE.getTypeSizeInBits(Expr->getType());
2375517e702SDimitry Andric ConstantRange AccessStartRange = SE.getUnsignedRange(Expr);
2383ca95b02SDimitry Andric ConstantRange SizeRange =
2393ca95b02SDimitry Andric ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize));
2403ca95b02SDimitry Andric ConstantRange AccessRange = AccessStartRange.add(SizeRange);
2413ca95b02SDimitry Andric ConstantRange AllocaRange =
2423ca95b02SDimitry Andric ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize));
2433ca95b02SDimitry Andric bool Safe = AllocaRange.contains(AccessRange);
2443ca95b02SDimitry Andric
2454ba319b5SDimitry Andric LLVM_DEBUG(
2464ba319b5SDimitry Andric dbgs() << "[SafeStack] "
2473ca95b02SDimitry Andric << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
2483ca95b02SDimitry Andric << *AllocaPtr << "\n"
2493ca95b02SDimitry Andric << " Access " << *Addr << "\n"
2503ca95b02SDimitry Andric << " SCEV " << *Expr
2515517e702SDimitry Andric << " U: " << SE.getUnsignedRange(Expr)
2525517e702SDimitry Andric << ", S: " << SE.getSignedRange(Expr) << "\n"
2533ca95b02SDimitry Andric << " Range " << AccessRange << "\n"
2543ca95b02SDimitry Andric << " AllocaRange " << AllocaRange << "\n"
2553ca95b02SDimitry Andric << " " << (Safe ? "safe" : "unsafe") << "\n");
2563ca95b02SDimitry Andric
2573ca95b02SDimitry Andric return Safe;
2583ca95b02SDimitry Andric }
2593ca95b02SDimitry Andric
IsMemIntrinsicSafe(const MemIntrinsic * MI,const Use & U,const Value * AllocaPtr,uint64_t AllocaSize)2603ca95b02SDimitry Andric bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
2613ca95b02SDimitry Andric const Value *AllocaPtr,
2623ca95b02SDimitry Andric uint64_t AllocaSize) {
263*b5893f02SDimitry Andric if (auto MTI = dyn_cast<MemTransferInst>(MI)) {
264*b5893f02SDimitry Andric if (MTI->getRawSource() != U && MTI->getRawDest() != U)
265*b5893f02SDimitry Andric return true;
266*b5893f02SDimitry Andric } else {
267*b5893f02SDimitry Andric if (MI->getRawDest() != U)
268*b5893f02SDimitry Andric return true;
269*b5893f02SDimitry Andric }
270*b5893f02SDimitry Andric
2713ca95b02SDimitry Andric const auto *Len = dyn_cast<ConstantInt>(MI->getLength());
2723ca95b02SDimitry Andric // Non-constant size => unsafe. FIXME: try SCEV getRange.
2733ca95b02SDimitry Andric if (!Len) return false;
2743ca95b02SDimitry Andric return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
2753ca95b02SDimitry Andric }
2763ca95b02SDimitry Andric
2773ca95b02SDimitry Andric /// Check whether a given allocation must be put on the safe
2783ca95b02SDimitry Andric /// stack or not. The function analyzes all uses of AI and checks whether it is
2793ca95b02SDimitry Andric /// only accessed in a memory safe way (as decided statically).
IsSafeStackAlloca(const Value * AllocaPtr,uint64_t AllocaSize)2803ca95b02SDimitry Andric bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) {
2813ca95b02SDimitry Andric // Go through all uses of this alloca and check whether all accesses to the
2823ca95b02SDimitry Andric // allocated object are statically known to be memory safe and, hence, the
2833ca95b02SDimitry Andric // object can be placed on the safe stack.
2843ca95b02SDimitry Andric SmallPtrSet<const Value *, 16> Visited;
2853ca95b02SDimitry Andric SmallVector<const Value *, 8> WorkList;
2863ca95b02SDimitry Andric WorkList.push_back(AllocaPtr);
2873ca95b02SDimitry Andric
2883ca95b02SDimitry Andric // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
2893ca95b02SDimitry Andric while (!WorkList.empty()) {
2903ca95b02SDimitry Andric const Value *V = WorkList.pop_back_val();
2913ca95b02SDimitry Andric for (const Use &UI : V->uses()) {
2923ca95b02SDimitry Andric auto I = cast<const Instruction>(UI.getUser());
2933ca95b02SDimitry Andric assert(V == UI.get());
2943ca95b02SDimitry Andric
2953ca95b02SDimitry Andric switch (I->getOpcode()) {
2962cab237bSDimitry Andric case Instruction::Load:
2975517e702SDimitry Andric if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getType()), AllocaPtr,
2983ca95b02SDimitry Andric AllocaSize))
2993ca95b02SDimitry Andric return false;
3003ca95b02SDimitry Andric break;
3012cab237bSDimitry Andric
3023ca95b02SDimitry Andric case Instruction::VAArg:
3033ca95b02SDimitry Andric // "va-arg" from a pointer is safe.
3043ca95b02SDimitry Andric break;
3052cab237bSDimitry Andric case Instruction::Store:
3063ca95b02SDimitry Andric if (V == I->getOperand(0)) {
3073ca95b02SDimitry Andric // Stored the pointer - conservatively assume it may be unsafe.
3084ba319b5SDimitry Andric LLVM_DEBUG(dbgs()
3094ba319b5SDimitry Andric << "[SafeStack] Unsafe alloca: " << *AllocaPtr
3103ca95b02SDimitry Andric << "\n store of address: " << *I << "\n");
3113ca95b02SDimitry Andric return false;
3123ca95b02SDimitry Andric }
3133ca95b02SDimitry Andric
3145517e702SDimitry Andric if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getOperand(0)->getType()),
3153ca95b02SDimitry Andric AllocaPtr, AllocaSize))
3163ca95b02SDimitry Andric return false;
3173ca95b02SDimitry Andric break;
3182cab237bSDimitry Andric
3192cab237bSDimitry Andric case Instruction::Ret:
3203ca95b02SDimitry Andric // Information leak.
3213ca95b02SDimitry Andric return false;
3223ca95b02SDimitry Andric
3233ca95b02SDimitry Andric case Instruction::Call:
3243ca95b02SDimitry Andric case Instruction::Invoke: {
3253ca95b02SDimitry Andric ImmutableCallSite CS(I);
3263ca95b02SDimitry Andric
327*b5893f02SDimitry Andric if (I->isLifetimeStartOrEnd())
3283ca95b02SDimitry Andric continue;
3293ca95b02SDimitry Andric
3303ca95b02SDimitry Andric if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
3313ca95b02SDimitry Andric if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
3324ba319b5SDimitry Andric LLVM_DEBUG(dbgs()
3334ba319b5SDimitry Andric << "[SafeStack] Unsafe alloca: " << *AllocaPtr
3344ba319b5SDimitry Andric << "\n unsafe memintrinsic: " << *I << "\n");
3353ca95b02SDimitry Andric return false;
3363ca95b02SDimitry Andric }
3373ca95b02SDimitry Andric continue;
3383ca95b02SDimitry Andric }
3393ca95b02SDimitry Andric
3403ca95b02SDimitry Andric // LLVM 'nocapture' attribute is only set for arguments whose address
3413ca95b02SDimitry Andric // is not stored, passed around, or used in any other non-trivial way.
3423ca95b02SDimitry Andric // We assume that passing a pointer to an object as a 'nocapture
3433ca95b02SDimitry Andric // readnone' argument is safe.
3443ca95b02SDimitry Andric // FIXME: a more precise solution would require an interprocedural
3453ca95b02SDimitry Andric // analysis here, which would look at all uses of an argument inside
3463ca95b02SDimitry Andric // the function being called.
3473ca95b02SDimitry Andric ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
3483ca95b02SDimitry Andric for (ImmutableCallSite::arg_iterator A = B; A != E; ++A)
3493ca95b02SDimitry Andric if (A->get() == V)
3503ca95b02SDimitry Andric if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) ||
3513ca95b02SDimitry Andric CS.doesNotAccessMemory()))) {
3524ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
3533ca95b02SDimitry Andric << "\n unsafe call: " << *I << "\n");
3543ca95b02SDimitry Andric return false;
3553ca95b02SDimitry Andric }
3563ca95b02SDimitry Andric continue;
3573ca95b02SDimitry Andric }
3583ca95b02SDimitry Andric
3593ca95b02SDimitry Andric default:
3603ca95b02SDimitry Andric if (Visited.insert(I).second)
3613ca95b02SDimitry Andric WorkList.push_back(cast<const Instruction>(I));
3623ca95b02SDimitry Andric }
3633ca95b02SDimitry Andric }
3643ca95b02SDimitry Andric }
3653ca95b02SDimitry Andric
3663ca95b02SDimitry Andric // All uses of the alloca are safe, we can place it on the safe stack.
3673ca95b02SDimitry Andric return true;
3683ca95b02SDimitry Andric }
3693ca95b02SDimitry Andric
getStackGuard(IRBuilder<> & IRB,Function & F)3703ca95b02SDimitry Andric Value *SafeStack::getStackGuard(IRBuilder<> &IRB, Function &F) {
3715517e702SDimitry Andric Value *StackGuardVar = TL.getIRStackGuard(IRB);
3723ca95b02SDimitry Andric if (!StackGuardVar)
3733ca95b02SDimitry Andric StackGuardVar =
3743ca95b02SDimitry Andric F.getParent()->getOrInsertGlobal("__stack_chk_guard", StackPtrTy);
3753ca95b02SDimitry Andric return IRB.CreateLoad(StackGuardVar, "StackGuard");
3763ca95b02SDimitry Andric }
3773ca95b02SDimitry Andric
findInsts(Function & F,SmallVectorImpl<AllocaInst * > & StaticAllocas,SmallVectorImpl<AllocaInst * > & DynamicAllocas,SmallVectorImpl<Argument * > & ByValArguments,SmallVectorImpl<ReturnInst * > & Returns,SmallVectorImpl<Instruction * > & StackRestorePoints)3783ca95b02SDimitry Andric void SafeStack::findInsts(Function &F,
3793ca95b02SDimitry Andric SmallVectorImpl<AllocaInst *> &StaticAllocas,
3803ca95b02SDimitry Andric SmallVectorImpl<AllocaInst *> &DynamicAllocas,
3813ca95b02SDimitry Andric SmallVectorImpl<Argument *> &ByValArguments,
3823ca95b02SDimitry Andric SmallVectorImpl<ReturnInst *> &Returns,
3833ca95b02SDimitry Andric SmallVectorImpl<Instruction *> &StackRestorePoints) {
3843ca95b02SDimitry Andric for (Instruction &I : instructions(&F)) {
3853ca95b02SDimitry Andric if (auto AI = dyn_cast<AllocaInst>(&I)) {
3863ca95b02SDimitry Andric ++NumAllocas;
3873ca95b02SDimitry Andric
3883ca95b02SDimitry Andric uint64_t Size = getStaticAllocaAllocationSize(AI);
3893ca95b02SDimitry Andric if (IsSafeStackAlloca(AI, Size))
3903ca95b02SDimitry Andric continue;
3913ca95b02SDimitry Andric
3923ca95b02SDimitry Andric if (AI->isStaticAlloca()) {
3933ca95b02SDimitry Andric ++NumUnsafeStaticAllocas;
3943ca95b02SDimitry Andric StaticAllocas.push_back(AI);
3953ca95b02SDimitry Andric } else {
3963ca95b02SDimitry Andric ++NumUnsafeDynamicAllocas;
3973ca95b02SDimitry Andric DynamicAllocas.push_back(AI);
3983ca95b02SDimitry Andric }
3993ca95b02SDimitry Andric } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
4003ca95b02SDimitry Andric Returns.push_back(RI);
4013ca95b02SDimitry Andric } else if (auto CI = dyn_cast<CallInst>(&I)) {
4023ca95b02SDimitry Andric // setjmps require stack restore.
4033ca95b02SDimitry Andric if (CI->getCalledFunction() && CI->canReturnTwice())
4043ca95b02SDimitry Andric StackRestorePoints.push_back(CI);
4053ca95b02SDimitry Andric } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
4063ca95b02SDimitry Andric // Exception landing pads require stack restore.
4073ca95b02SDimitry Andric StackRestorePoints.push_back(LP);
4083ca95b02SDimitry Andric } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
4093ca95b02SDimitry Andric if (II->getIntrinsicID() == Intrinsic::gcroot)
4102cab237bSDimitry Andric report_fatal_error(
4113ca95b02SDimitry Andric "gcroot intrinsic not compatible with safestack attribute");
4123ca95b02SDimitry Andric }
4133ca95b02SDimitry Andric }
4143ca95b02SDimitry Andric for (Argument &Arg : F.args()) {
4153ca95b02SDimitry Andric if (!Arg.hasByValAttr())
4163ca95b02SDimitry Andric continue;
4173ca95b02SDimitry Andric uint64_t Size =
4185517e702SDimitry Andric DL.getTypeStoreSize(Arg.getType()->getPointerElementType());
4193ca95b02SDimitry Andric if (IsSafeStackAlloca(&Arg, Size))
4203ca95b02SDimitry Andric continue;
4213ca95b02SDimitry Andric
4223ca95b02SDimitry Andric ++NumUnsafeByValArguments;
4233ca95b02SDimitry Andric ByValArguments.push_back(&Arg);
4243ca95b02SDimitry Andric }
4253ca95b02SDimitry Andric }
4263ca95b02SDimitry Andric
4273ca95b02SDimitry Andric AllocaInst *
createStackRestorePoints(IRBuilder<> & IRB,Function & F,ArrayRef<Instruction * > StackRestorePoints,Value * StaticTop,bool NeedDynamicTop)4283ca95b02SDimitry Andric SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
4293ca95b02SDimitry Andric ArrayRef<Instruction *> StackRestorePoints,
4303ca95b02SDimitry Andric Value *StaticTop, bool NeedDynamicTop) {
4313ca95b02SDimitry Andric assert(StaticTop && "The stack top isn't set.");
4323ca95b02SDimitry Andric
4333ca95b02SDimitry Andric if (StackRestorePoints.empty())
4343ca95b02SDimitry Andric return nullptr;
4353ca95b02SDimitry Andric
4363ca95b02SDimitry Andric // We need the current value of the shadow stack pointer to restore
4373ca95b02SDimitry Andric // after longjmp or exception catching.
4383ca95b02SDimitry Andric
4393ca95b02SDimitry Andric // FIXME: On some platforms this could be handled by the longjmp/exception
4403ca95b02SDimitry Andric // runtime itself.
4413ca95b02SDimitry Andric
4423ca95b02SDimitry Andric AllocaInst *DynamicTop = nullptr;
4433ca95b02SDimitry Andric if (NeedDynamicTop) {
4443ca95b02SDimitry Andric // If we also have dynamic alloca's, the stack pointer value changes
4453ca95b02SDimitry Andric // throughout the function. For now we store it in an alloca.
4463ca95b02SDimitry Andric DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
4473ca95b02SDimitry Andric "unsafe_stack_dynamic_ptr");
4483ca95b02SDimitry Andric IRB.CreateStore(StaticTop, DynamicTop);
4493ca95b02SDimitry Andric }
4503ca95b02SDimitry Andric
4513ca95b02SDimitry Andric // Restore current stack pointer after longjmp/exception catch.
4523ca95b02SDimitry Andric for (Instruction *I : StackRestorePoints) {
4533ca95b02SDimitry Andric ++NumUnsafeStackRestorePoints;
4543ca95b02SDimitry Andric
4553ca95b02SDimitry Andric IRB.SetInsertPoint(I->getNextNode());
4563ca95b02SDimitry Andric Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
4573ca95b02SDimitry Andric IRB.CreateStore(CurrentTop, UnsafeStackPtr);
4583ca95b02SDimitry Andric }
4593ca95b02SDimitry Andric
4603ca95b02SDimitry Andric return DynamicTop;
4613ca95b02SDimitry Andric }
4623ca95b02SDimitry Andric
checkStackGuard(IRBuilder<> & IRB,Function & F,ReturnInst & RI,AllocaInst * StackGuardSlot,Value * StackGuard)4633ca95b02SDimitry Andric void SafeStack::checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
4643ca95b02SDimitry Andric AllocaInst *StackGuardSlot, Value *StackGuard) {
4653ca95b02SDimitry Andric Value *V = IRB.CreateLoad(StackGuardSlot);
4663ca95b02SDimitry Andric Value *Cmp = IRB.CreateICmpNE(StackGuard, V);
4673ca95b02SDimitry Andric
4683ca95b02SDimitry Andric auto SuccessProb = BranchProbabilityInfo::getBranchProbStackProtector(true);
4693ca95b02SDimitry Andric auto FailureProb = BranchProbabilityInfo::getBranchProbStackProtector(false);
4703ca95b02SDimitry Andric MDNode *Weights = MDBuilder(F.getContext())
4713ca95b02SDimitry Andric .createBranchWeights(SuccessProb.getNumerator(),
4723ca95b02SDimitry Andric FailureProb.getNumerator());
4733ca95b02SDimitry Andric Instruction *CheckTerm =
4743ca95b02SDimitry Andric SplitBlockAndInsertIfThen(Cmp, &RI,
4753ca95b02SDimitry Andric /* Unreachable */ true, Weights);
4763ca95b02SDimitry Andric IRBuilder<> IRBFail(CheckTerm);
4773ca95b02SDimitry Andric // FIXME: respect -fsanitize-trap / -ftrap-function here?
4783ca95b02SDimitry Andric Constant *StackChkFail = F.getParent()->getOrInsertFunction(
4797a7e6055SDimitry Andric "__stack_chk_fail", IRB.getVoidTy());
4803ca95b02SDimitry Andric IRBFail.CreateCall(StackChkFail, {});
4813ca95b02SDimitry Andric }
4823ca95b02SDimitry Andric
4833ca95b02SDimitry Andric /// We explicitly compute and set the unsafe stack layout for all unsafe
4843ca95b02SDimitry Andric /// static alloca instructions. We save the unsafe "base pointer" in the
4853ca95b02SDimitry Andric /// prologue into a local variable and restore it in the epilogue.
moveStaticAllocasToUnsafeStack(IRBuilder<> & IRB,Function & F,ArrayRef<AllocaInst * > StaticAllocas,ArrayRef<Argument * > ByValArguments,ArrayRef<ReturnInst * > Returns,Instruction * BasePointer,AllocaInst * StackGuardSlot)4863ca95b02SDimitry Andric Value *SafeStack::moveStaticAllocasToUnsafeStack(
4873ca95b02SDimitry Andric IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
4883ca95b02SDimitry Andric ArrayRef<Argument *> ByValArguments, ArrayRef<ReturnInst *> Returns,
4893ca95b02SDimitry Andric Instruction *BasePointer, AllocaInst *StackGuardSlot) {
4903ca95b02SDimitry Andric if (StaticAllocas.empty() && ByValArguments.empty())
4913ca95b02SDimitry Andric return BasePointer;
4923ca95b02SDimitry Andric
4933ca95b02SDimitry Andric DIBuilder DIB(*F.getParent());
4943ca95b02SDimitry Andric
4953ca95b02SDimitry Andric StackColoring SSC(F, StaticAllocas);
4963ca95b02SDimitry Andric SSC.run();
4973ca95b02SDimitry Andric SSC.removeAllMarkers();
4983ca95b02SDimitry Andric
4993ca95b02SDimitry Andric // Unsafe stack always grows down.
5003ca95b02SDimitry Andric StackLayout SSL(StackAlignment);
5013ca95b02SDimitry Andric if (StackGuardSlot) {
5023ca95b02SDimitry Andric Type *Ty = StackGuardSlot->getAllocatedType();
5033ca95b02SDimitry Andric unsigned Align =
5045517e702SDimitry Andric std::max(DL.getPrefTypeAlignment(Ty), StackGuardSlot->getAlignment());
5053ca95b02SDimitry Andric SSL.addObject(StackGuardSlot, getStaticAllocaAllocationSize(StackGuardSlot),
5066c4bc1bdSDimitry Andric Align, SSC.getFullLiveRange());
5073ca95b02SDimitry Andric }
5083ca95b02SDimitry Andric
5093ca95b02SDimitry Andric for (Argument *Arg : ByValArguments) {
5103ca95b02SDimitry Andric Type *Ty = Arg->getType()->getPointerElementType();
5115517e702SDimitry Andric uint64_t Size = DL.getTypeStoreSize(Ty);
5123ca95b02SDimitry Andric if (Size == 0)
5133ca95b02SDimitry Andric Size = 1; // Don't create zero-sized stack objects.
5143ca95b02SDimitry Andric
5153ca95b02SDimitry Andric // Ensure the object is properly aligned.
5165517e702SDimitry Andric unsigned Align = std::max((unsigned)DL.getPrefTypeAlignment(Ty),
5173ca95b02SDimitry Andric Arg->getParamAlignment());
5183ca95b02SDimitry Andric SSL.addObject(Arg, Size, Align, SSC.getFullLiveRange());
5193ca95b02SDimitry Andric }
5203ca95b02SDimitry Andric
5213ca95b02SDimitry Andric for (AllocaInst *AI : StaticAllocas) {
5223ca95b02SDimitry Andric Type *Ty = AI->getAllocatedType();
5233ca95b02SDimitry Andric uint64_t Size = getStaticAllocaAllocationSize(AI);
5243ca95b02SDimitry Andric if (Size == 0)
5253ca95b02SDimitry Andric Size = 1; // Don't create zero-sized stack objects.
5263ca95b02SDimitry Andric
5273ca95b02SDimitry Andric // Ensure the object is properly aligned.
5283ca95b02SDimitry Andric unsigned Align =
5295517e702SDimitry Andric std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment());
5303ca95b02SDimitry Andric
5313ca95b02SDimitry Andric SSL.addObject(AI, Size, Align, SSC.getLiveRange(AI));
5323ca95b02SDimitry Andric }
5333ca95b02SDimitry Andric
5343ca95b02SDimitry Andric SSL.computeLayout();
5353ca95b02SDimitry Andric unsigned FrameAlignment = SSL.getFrameAlignment();
5363ca95b02SDimitry Andric
5373ca95b02SDimitry Andric // FIXME: tell SSL that we start at a less-then-MaxAlignment aligned location
5383ca95b02SDimitry Andric // (AlignmentSkew).
5393ca95b02SDimitry Andric if (FrameAlignment > StackAlignment) {
5403ca95b02SDimitry Andric // Re-align the base pointer according to the max requested alignment.
5413ca95b02SDimitry Andric assert(isPowerOf2_32(FrameAlignment));
5423ca95b02SDimitry Andric IRB.SetInsertPoint(BasePointer->getNextNode());
5433ca95b02SDimitry Andric BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
5443ca95b02SDimitry Andric IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
5453ca95b02SDimitry Andric ConstantInt::get(IntPtrTy, ~uint64_t(FrameAlignment - 1))),
5463ca95b02SDimitry Andric StackPtrTy));
5473ca95b02SDimitry Andric }
5483ca95b02SDimitry Andric
5493ca95b02SDimitry Andric IRB.SetInsertPoint(BasePointer->getNextNode());
5503ca95b02SDimitry Andric
5513ca95b02SDimitry Andric if (StackGuardSlot) {
5523ca95b02SDimitry Andric unsigned Offset = SSL.getObjectOffset(StackGuardSlot);
5533ca95b02SDimitry Andric Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
5543ca95b02SDimitry Andric ConstantInt::get(Int32Ty, -Offset));
5553ca95b02SDimitry Andric Value *NewAI =
5563ca95b02SDimitry Andric IRB.CreateBitCast(Off, StackGuardSlot->getType(), "StackGuardSlot");
5573ca95b02SDimitry Andric
5583ca95b02SDimitry Andric // Replace alloc with the new location.
5593ca95b02SDimitry Andric StackGuardSlot->replaceAllUsesWith(NewAI);
5603ca95b02SDimitry Andric StackGuardSlot->eraseFromParent();
5613ca95b02SDimitry Andric }
5623ca95b02SDimitry Andric
5633ca95b02SDimitry Andric for (Argument *Arg : ByValArguments) {
5643ca95b02SDimitry Andric unsigned Offset = SSL.getObjectOffset(Arg);
5654ba319b5SDimitry Andric unsigned Align = SSL.getObjectAlignment(Arg);
5663ca95b02SDimitry Andric Type *Ty = Arg->getType()->getPointerElementType();
5673ca95b02SDimitry Andric
5685517e702SDimitry Andric uint64_t Size = DL.getTypeStoreSize(Ty);
5693ca95b02SDimitry Andric if (Size == 0)
5703ca95b02SDimitry Andric Size = 1; // Don't create zero-sized stack objects.
5713ca95b02SDimitry Andric
5723ca95b02SDimitry Andric Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
5733ca95b02SDimitry Andric ConstantInt::get(Int32Ty, -Offset));
5743ca95b02SDimitry Andric Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
5753ca95b02SDimitry Andric Arg->getName() + ".unsafe-byval");
5763ca95b02SDimitry Andric
5773ca95b02SDimitry Andric // Replace alloc with the new location.
5783ca95b02SDimitry Andric replaceDbgDeclare(Arg, BasePointer, BasePointer->getNextNode(), DIB,
5792cab237bSDimitry Andric DIExpression::NoDeref, -Offset, DIExpression::NoDeref);
5803ca95b02SDimitry Andric Arg->replaceAllUsesWith(NewArg);
5813ca95b02SDimitry Andric IRB.SetInsertPoint(cast<Instruction>(NewArg)->getNextNode());
5824ba319b5SDimitry Andric IRB.CreateMemCpy(Off, Align, Arg, Arg->getParamAlignment(), Size);
5833ca95b02SDimitry Andric }
5843ca95b02SDimitry Andric
5853ca95b02SDimitry Andric // Allocate space for every unsafe static AllocaInst on the unsafe stack.
5863ca95b02SDimitry Andric for (AllocaInst *AI : StaticAllocas) {
5873ca95b02SDimitry Andric IRB.SetInsertPoint(AI);
5883ca95b02SDimitry Andric unsigned Offset = SSL.getObjectOffset(AI);
5893ca95b02SDimitry Andric
5903ca95b02SDimitry Andric uint64_t Size = getStaticAllocaAllocationSize(AI);
5913ca95b02SDimitry Andric if (Size == 0)
5923ca95b02SDimitry Andric Size = 1; // Don't create zero-sized stack objects.
5933ca95b02SDimitry Andric
5942cab237bSDimitry Andric replaceDbgDeclareForAlloca(AI, BasePointer, DIB, DIExpression::NoDeref,
5952cab237bSDimitry Andric -Offset, DIExpression::NoDeref);
5963ca95b02SDimitry Andric replaceDbgValueForAlloca(AI, BasePointer, DIB, -Offset);
5973ca95b02SDimitry Andric
5983ca95b02SDimitry Andric // Replace uses of the alloca with the new location.
5993ca95b02SDimitry Andric // Insert address calculation close to each use to work around PR27844.
6003ca95b02SDimitry Andric std::string Name = std::string(AI->getName()) + ".unsafe";
6013ca95b02SDimitry Andric while (!AI->use_empty()) {
6023ca95b02SDimitry Andric Use &U = *AI->use_begin();
6033ca95b02SDimitry Andric Instruction *User = cast<Instruction>(U.getUser());
6043ca95b02SDimitry Andric
6053ca95b02SDimitry Andric Instruction *InsertBefore;
6063ca95b02SDimitry Andric if (auto *PHI = dyn_cast<PHINode>(User))
6073ca95b02SDimitry Andric InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
6083ca95b02SDimitry Andric else
6093ca95b02SDimitry Andric InsertBefore = User;
6103ca95b02SDimitry Andric
6113ca95b02SDimitry Andric IRBuilder<> IRBUser(InsertBefore);
6123ca95b02SDimitry Andric Value *Off = IRBUser.CreateGEP(BasePointer, // BasePointer is i8*
6133ca95b02SDimitry Andric ConstantInt::get(Int32Ty, -Offset));
6143ca95b02SDimitry Andric Value *Replacement = IRBUser.CreateBitCast(Off, AI->getType(), Name);
6153ca95b02SDimitry Andric
6163ca95b02SDimitry Andric if (auto *PHI = dyn_cast<PHINode>(User)) {
6173ca95b02SDimitry Andric // PHI nodes may have multiple incoming edges from the same BB (why??),
6183ca95b02SDimitry Andric // all must be updated at once with the same incoming value.
6193ca95b02SDimitry Andric auto *BB = PHI->getIncomingBlock(U);
6203ca95b02SDimitry Andric for (unsigned I = 0; I < PHI->getNumIncomingValues(); ++I)
6213ca95b02SDimitry Andric if (PHI->getIncomingBlock(I) == BB)
6223ca95b02SDimitry Andric PHI->setIncomingValue(I, Replacement);
6233ca95b02SDimitry Andric } else {
6243ca95b02SDimitry Andric U.set(Replacement);
6253ca95b02SDimitry Andric }
6263ca95b02SDimitry Andric }
6273ca95b02SDimitry Andric
6283ca95b02SDimitry Andric AI->eraseFromParent();
6293ca95b02SDimitry Andric }
6303ca95b02SDimitry Andric
6313ca95b02SDimitry Andric // Re-align BasePointer so that our callees would see it aligned as
6323ca95b02SDimitry Andric // expected.
6333ca95b02SDimitry Andric // FIXME: no need to update BasePointer in leaf functions.
6343ca95b02SDimitry Andric unsigned FrameSize = alignTo(SSL.getFrameSize(), StackAlignment);
6353ca95b02SDimitry Andric
6363ca95b02SDimitry Andric // Update shadow stack pointer in the function epilogue.
6373ca95b02SDimitry Andric IRB.SetInsertPoint(BasePointer->getNextNode());
6383ca95b02SDimitry Andric
6393ca95b02SDimitry Andric Value *StaticTop =
6403ca95b02SDimitry Andric IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -FrameSize),
6413ca95b02SDimitry Andric "unsafe_stack_static_top");
6423ca95b02SDimitry Andric IRB.CreateStore(StaticTop, UnsafeStackPtr);
6433ca95b02SDimitry Andric return StaticTop;
6443ca95b02SDimitry Andric }
6453ca95b02SDimitry Andric
moveDynamicAllocasToUnsafeStack(Function & F,Value * UnsafeStackPtr,AllocaInst * DynamicTop,ArrayRef<AllocaInst * > DynamicAllocas)6463ca95b02SDimitry Andric void SafeStack::moveDynamicAllocasToUnsafeStack(
6473ca95b02SDimitry Andric Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
6483ca95b02SDimitry Andric ArrayRef<AllocaInst *> DynamicAllocas) {
6493ca95b02SDimitry Andric DIBuilder DIB(*F.getParent());
6503ca95b02SDimitry Andric
6513ca95b02SDimitry Andric for (AllocaInst *AI : DynamicAllocas) {
6523ca95b02SDimitry Andric IRBuilder<> IRB(AI);
6533ca95b02SDimitry Andric
6543ca95b02SDimitry Andric // Compute the new SP value (after AI).
6553ca95b02SDimitry Andric Value *ArraySize = AI->getArraySize();
6563ca95b02SDimitry Andric if (ArraySize->getType() != IntPtrTy)
6573ca95b02SDimitry Andric ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
6583ca95b02SDimitry Andric
6593ca95b02SDimitry Andric Type *Ty = AI->getAllocatedType();
6605517e702SDimitry Andric uint64_t TySize = DL.getTypeAllocSize(Ty);
6613ca95b02SDimitry Andric Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
6623ca95b02SDimitry Andric
6633ca95b02SDimitry Andric Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy);
6643ca95b02SDimitry Andric SP = IRB.CreateSub(SP, Size);
6653ca95b02SDimitry Andric
6663ca95b02SDimitry Andric // Align the SP value to satisfy the AllocaInst, type and stack alignments.
6673ca95b02SDimitry Andric unsigned Align = std::max(
6685517e702SDimitry Andric std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment()),
6693ca95b02SDimitry Andric (unsigned)StackAlignment);
6703ca95b02SDimitry Andric
6713ca95b02SDimitry Andric assert(isPowerOf2_32(Align));
6723ca95b02SDimitry Andric Value *NewTop = IRB.CreateIntToPtr(
6733ca95b02SDimitry Andric IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
6743ca95b02SDimitry Andric StackPtrTy);
6753ca95b02SDimitry Andric
6763ca95b02SDimitry Andric // Save the stack pointer.
6773ca95b02SDimitry Andric IRB.CreateStore(NewTop, UnsafeStackPtr);
6783ca95b02SDimitry Andric if (DynamicTop)
6793ca95b02SDimitry Andric IRB.CreateStore(NewTop, DynamicTop);
6803ca95b02SDimitry Andric
6813ca95b02SDimitry Andric Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
6823ca95b02SDimitry Andric if (AI->hasName() && isa<Instruction>(NewAI))
6833ca95b02SDimitry Andric NewAI->takeName(AI);
6843ca95b02SDimitry Andric
6852cab237bSDimitry Andric replaceDbgDeclareForAlloca(AI, NewAI, DIB, DIExpression::NoDeref, 0,
6862cab237bSDimitry Andric DIExpression::NoDeref);
6873ca95b02SDimitry Andric AI->replaceAllUsesWith(NewAI);
6883ca95b02SDimitry Andric AI->eraseFromParent();
6893ca95b02SDimitry Andric }
6903ca95b02SDimitry Andric
6913ca95b02SDimitry Andric if (!DynamicAllocas.empty()) {
6923ca95b02SDimitry Andric // Now go through the instructions again, replacing stacksave/stackrestore.
6933ca95b02SDimitry Andric for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
6943ca95b02SDimitry Andric Instruction *I = &*(It++);
6953ca95b02SDimitry Andric auto II = dyn_cast<IntrinsicInst>(I);
6963ca95b02SDimitry Andric if (!II)
6973ca95b02SDimitry Andric continue;
6983ca95b02SDimitry Andric
6993ca95b02SDimitry Andric if (II->getIntrinsicID() == Intrinsic::stacksave) {
7003ca95b02SDimitry Andric IRBuilder<> IRB(II);
7013ca95b02SDimitry Andric Instruction *LI = IRB.CreateLoad(UnsafeStackPtr);
7023ca95b02SDimitry Andric LI->takeName(II);
7033ca95b02SDimitry Andric II->replaceAllUsesWith(LI);
7043ca95b02SDimitry Andric II->eraseFromParent();
7053ca95b02SDimitry Andric } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
7063ca95b02SDimitry Andric IRBuilder<> IRB(II);
7073ca95b02SDimitry Andric Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
7083ca95b02SDimitry Andric SI->takeName(II);
7093ca95b02SDimitry Andric assert(II->use_empty());
7103ca95b02SDimitry Andric II->eraseFromParent();
7113ca95b02SDimitry Andric }
7123ca95b02SDimitry Andric }
7133ca95b02SDimitry Andric }
7143ca95b02SDimitry Andric }
7153ca95b02SDimitry Andric
ShouldInlinePointerAddress(CallSite & CS)7164ba319b5SDimitry Andric bool SafeStack::ShouldInlinePointerAddress(CallSite &CS) {
7174ba319b5SDimitry Andric Function *Callee = CS.getCalledFunction();
7184ba319b5SDimitry Andric if (CS.hasFnAttr(Attribute::AlwaysInline) && isInlineViable(*Callee))
7194ba319b5SDimitry Andric return true;
7204ba319b5SDimitry Andric if (Callee->isInterposable() || Callee->hasFnAttribute(Attribute::NoInline) ||
7214ba319b5SDimitry Andric CS.isNoInline())
7224ba319b5SDimitry Andric return false;
7234ba319b5SDimitry Andric return true;
7244ba319b5SDimitry Andric }
7254ba319b5SDimitry Andric
TryInlinePointerAddress()7264ba319b5SDimitry Andric void SafeStack::TryInlinePointerAddress() {
7274ba319b5SDimitry Andric if (!isa<CallInst>(UnsafeStackPtr))
7284ba319b5SDimitry Andric return;
7294ba319b5SDimitry Andric
7304ba319b5SDimitry Andric if(F.hasFnAttribute(Attribute::OptimizeNone))
7314ba319b5SDimitry Andric return;
7324ba319b5SDimitry Andric
7334ba319b5SDimitry Andric CallSite CS(UnsafeStackPtr);
7344ba319b5SDimitry Andric Function *Callee = CS.getCalledFunction();
7354ba319b5SDimitry Andric if (!Callee || Callee->isDeclaration())
7364ba319b5SDimitry Andric return;
7374ba319b5SDimitry Andric
7384ba319b5SDimitry Andric if (!ShouldInlinePointerAddress(CS))
7394ba319b5SDimitry Andric return;
7404ba319b5SDimitry Andric
7414ba319b5SDimitry Andric InlineFunctionInfo IFI;
7424ba319b5SDimitry Andric InlineFunction(CS, IFI);
7434ba319b5SDimitry Andric }
7444ba319b5SDimitry Andric
run()7455517e702SDimitry Andric bool SafeStack::run() {
7465517e702SDimitry Andric assert(F.hasFnAttribute(Attribute::SafeStack) &&
7475517e702SDimitry Andric "Can't run SafeStack on a function without the attribute");
7485517e702SDimitry Andric assert(!F.isDeclaration() && "Can't run SafeStack on a function declaration");
7493ca95b02SDimitry Andric
7503ca95b02SDimitry Andric ++NumFunctions;
7513ca95b02SDimitry Andric
7523ca95b02SDimitry Andric SmallVector<AllocaInst *, 16> StaticAllocas;
7533ca95b02SDimitry Andric SmallVector<AllocaInst *, 4> DynamicAllocas;
7543ca95b02SDimitry Andric SmallVector<Argument *, 4> ByValArguments;
7553ca95b02SDimitry Andric SmallVector<ReturnInst *, 4> Returns;
7563ca95b02SDimitry Andric
7573ca95b02SDimitry Andric // Collect all points where stack gets unwound and needs to be restored
7583ca95b02SDimitry Andric // This is only necessary because the runtime (setjmp and unwind code) is
759d88c1a5aSDimitry Andric // not aware of the unsafe stack and won't unwind/restore it properly.
7603ca95b02SDimitry Andric // To work around this problem without changing the runtime, we insert
7613ca95b02SDimitry Andric // instrumentation to restore the unsafe stack pointer when necessary.
7623ca95b02SDimitry Andric SmallVector<Instruction *, 4> StackRestorePoints;
7633ca95b02SDimitry Andric
7643ca95b02SDimitry Andric // Find all static and dynamic alloca instructions that must be moved to the
7653ca95b02SDimitry Andric // unsafe stack, all return instructions and stack restore points.
7663ca95b02SDimitry Andric findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
7673ca95b02SDimitry Andric StackRestorePoints);
7683ca95b02SDimitry Andric
7693ca95b02SDimitry Andric if (StaticAllocas.empty() && DynamicAllocas.empty() &&
7703ca95b02SDimitry Andric ByValArguments.empty() && StackRestorePoints.empty())
7713ca95b02SDimitry Andric return false; // Nothing to do in this function.
7723ca95b02SDimitry Andric
7733ca95b02SDimitry Andric if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
7743ca95b02SDimitry Andric !ByValArguments.empty())
7753ca95b02SDimitry Andric ++NumUnsafeStackFunctions; // This function has the unsafe stack.
7763ca95b02SDimitry Andric
7773ca95b02SDimitry Andric if (!StackRestorePoints.empty())
7783ca95b02SDimitry Andric ++NumUnsafeStackRestorePointsFunctions;
7793ca95b02SDimitry Andric
7803ca95b02SDimitry Andric IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
781*b5893f02SDimitry Andric // Calls must always have a debug location, or else inlining breaks. So
782*b5893f02SDimitry Andric // we explicitly set a artificial debug location here.
783*b5893f02SDimitry Andric if (DISubprogram *SP = F.getSubprogram())
784*b5893f02SDimitry Andric IRB.SetCurrentDebugLocation(DebugLoc::get(SP->getScopeLine(), 0, SP));
7854ba319b5SDimitry Andric if (SafeStackUsePointerAddress) {
7864ba319b5SDimitry Andric Value *Fn = F.getParent()->getOrInsertFunction(
7874ba319b5SDimitry Andric "__safestack_pointer_address", StackPtrTy->getPointerTo(0));
7884ba319b5SDimitry Andric UnsafeStackPtr = IRB.CreateCall(Fn);
7894ba319b5SDimitry Andric } else {
7905517e702SDimitry Andric UnsafeStackPtr = TL.getSafeStackPointerLocation(IRB);
7914ba319b5SDimitry Andric }
7923ca95b02SDimitry Andric
7933ca95b02SDimitry Andric // Load the current stack pointer (we'll also use it as a base pointer).
7943ca95b02SDimitry Andric // FIXME: use a dedicated register for it ?
7953ca95b02SDimitry Andric Instruction *BasePointer =
7963ca95b02SDimitry Andric IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
7973ca95b02SDimitry Andric assert(BasePointer->getType() == StackPtrTy);
7983ca95b02SDimitry Andric
7993ca95b02SDimitry Andric AllocaInst *StackGuardSlot = nullptr;
8003ca95b02SDimitry Andric // FIXME: implement weaker forms of stack protector.
8013ca95b02SDimitry Andric if (F.hasFnAttribute(Attribute::StackProtect) ||
8023ca95b02SDimitry Andric F.hasFnAttribute(Attribute::StackProtectStrong) ||
8033ca95b02SDimitry Andric F.hasFnAttribute(Attribute::StackProtectReq)) {
8043ca95b02SDimitry Andric Value *StackGuard = getStackGuard(IRB, F);
8053ca95b02SDimitry Andric StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr);
8063ca95b02SDimitry Andric IRB.CreateStore(StackGuard, StackGuardSlot);
8073ca95b02SDimitry Andric
8083ca95b02SDimitry Andric for (ReturnInst *RI : Returns) {
8093ca95b02SDimitry Andric IRBuilder<> IRBRet(RI);
8103ca95b02SDimitry Andric checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
8113ca95b02SDimitry Andric }
8123ca95b02SDimitry Andric }
8133ca95b02SDimitry Andric
8143ca95b02SDimitry Andric // The top of the unsafe stack after all unsafe static allocas are
8153ca95b02SDimitry Andric // allocated.
8163ca95b02SDimitry Andric Value *StaticTop =
8173ca95b02SDimitry Andric moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, ByValArguments,
8183ca95b02SDimitry Andric Returns, BasePointer, StackGuardSlot);
8193ca95b02SDimitry Andric
8203ca95b02SDimitry Andric // Safe stack object that stores the current unsafe stack top. It is updated
8213ca95b02SDimitry Andric // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
8223ca95b02SDimitry Andric // This is only needed if we need to restore stack pointer after longjmp
8233ca95b02SDimitry Andric // or exceptions, and we have dynamic allocations.
8243ca95b02SDimitry Andric // FIXME: a better alternative might be to store the unsafe stack pointer
8253ca95b02SDimitry Andric // before setjmp / invoke instructions.
8263ca95b02SDimitry Andric AllocaInst *DynamicTop = createStackRestorePoints(
8273ca95b02SDimitry Andric IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
8283ca95b02SDimitry Andric
8293ca95b02SDimitry Andric // Handle dynamic allocas.
8303ca95b02SDimitry Andric moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
8313ca95b02SDimitry Andric DynamicAllocas);
8323ca95b02SDimitry Andric
8333ca95b02SDimitry Andric // Restore the unsafe stack pointer before each return.
8343ca95b02SDimitry Andric for (ReturnInst *RI : Returns) {
8353ca95b02SDimitry Andric IRB.SetInsertPoint(RI);
8363ca95b02SDimitry Andric IRB.CreateStore(BasePointer, UnsafeStackPtr);
8373ca95b02SDimitry Andric }
8383ca95b02SDimitry Andric
8394ba319b5SDimitry Andric TryInlinePointerAddress();
8404ba319b5SDimitry Andric
8414ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "[SafeStack] safestack applied\n");
8423ca95b02SDimitry Andric return true;
8433ca95b02SDimitry Andric }
8443ca95b02SDimitry Andric
8455517e702SDimitry Andric class SafeStackLegacyPass : public FunctionPass {
8462cab237bSDimitry Andric const TargetMachine *TM = nullptr;
8475517e702SDimitry Andric
8485517e702SDimitry Andric public:
8495517e702SDimitry Andric static char ID; // Pass identification, replacement for typeid..
8502cab237bSDimitry Andric
SafeStackLegacyPass()8512cab237bSDimitry Andric SafeStackLegacyPass() : FunctionPass(ID) {
8525517e702SDimitry Andric initializeSafeStackLegacyPassPass(*PassRegistry::getPassRegistry());
8535517e702SDimitry Andric }
8545517e702SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const8555517e702SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
856d8866befSDimitry Andric AU.addRequired<TargetPassConfig>();
8575517e702SDimitry Andric AU.addRequired<TargetLibraryInfoWrapperPass>();
8585517e702SDimitry Andric AU.addRequired<AssumptionCacheTracker>();
8595517e702SDimitry Andric }
8605517e702SDimitry Andric
runOnFunction(Function & F)8615517e702SDimitry Andric bool runOnFunction(Function &F) override {
8624ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
8635517e702SDimitry Andric
8645517e702SDimitry Andric if (!F.hasFnAttribute(Attribute::SafeStack)) {
8654ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "[SafeStack] safestack is not requested"
8665517e702SDimitry Andric " for this function\n");
8675517e702SDimitry Andric return false;
8685517e702SDimitry Andric }
8695517e702SDimitry Andric
8705517e702SDimitry Andric if (F.isDeclaration()) {
8714ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "[SafeStack] function definition"
8725517e702SDimitry Andric " is not available\n");
8735517e702SDimitry Andric return false;
8745517e702SDimitry Andric }
8755517e702SDimitry Andric
876d8866befSDimitry Andric TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
8775517e702SDimitry Andric auto *TL = TM->getSubtargetImpl(F)->getTargetLowering();
8785517e702SDimitry Andric if (!TL)
8795517e702SDimitry Andric report_fatal_error("TargetLowering instance is required");
8805517e702SDimitry Andric
8815517e702SDimitry Andric auto *DL = &F.getParent()->getDataLayout();
8825517e702SDimitry Andric auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
8835517e702SDimitry Andric auto &ACT = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8845517e702SDimitry Andric
8855517e702SDimitry Andric // Compute DT and LI only for functions that have the attribute.
8865517e702SDimitry Andric // This is only useful because the legacy pass manager doesn't let us
8875517e702SDimitry Andric // compute analyzes lazily.
8885517e702SDimitry Andric // In the backend pipeline, nothing preserves DT before SafeStack, so we
8895517e702SDimitry Andric // would otherwise always compute it wastefully, even if there is no
8905517e702SDimitry Andric // function with the safestack attribute.
8915517e702SDimitry Andric DominatorTree DT(F);
8925517e702SDimitry Andric LoopInfo LI(DT);
8935517e702SDimitry Andric
8945517e702SDimitry Andric ScalarEvolution SE(F, TLI, ACT, DT, LI);
8955517e702SDimitry Andric
8965517e702SDimitry Andric return SafeStack(F, *TL, *DL, SE).run();
8975517e702SDimitry Andric }
8985517e702SDimitry Andric };
8995517e702SDimitry Andric
9002cab237bSDimitry Andric } // end anonymous namespace
9013ca95b02SDimitry Andric
9025517e702SDimitry Andric char SafeStackLegacyPass::ID = 0;
9032cab237bSDimitry Andric
904302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(SafeStackLegacyPass, DEBUG_TYPE,
9053ca95b02SDimitry Andric "Safe Stack instrumentation pass", false, false)
INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)906d8866befSDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
907302affcbSDimitry Andric INITIALIZE_PASS_END(SafeStackLegacyPass, DEBUG_TYPE,
9083ca95b02SDimitry Andric "Safe Stack instrumentation pass", false, false)
9093ca95b02SDimitry Andric
910d8866befSDimitry Andric FunctionPass *llvm::createSafeStackPass() { return new SafeStackLegacyPass(); }
911