blob: b4a2ec436db087aadd80af2e4f140c78a8169d99 [file] [log] [blame]
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001//===-- SafeStack.cpp - Safe Stack Insertion ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass splits the stack into the safe stack (kept as-is for LLVM backend)
11// and the unsafe stack (explicitly allocated and managed through the runtime
12// support library).
13//
14// http://clang.llvm.org/docs/SafeStack.html
15//
16//===----------------------------------------------------------------------===//
17
Peter Collingbourne82437bf2015-06-15 21:07:11 +000018#include "llvm/ADT/Statistic.h"
19#include "llvm/ADT/Triple.h"
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +000020#include "llvm/Analysis/BranchProbabilityInfo.h"
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000021#include "llvm/Analysis/ScalarEvolution.h"
22#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Evgeniy Stepanova2002b02015-09-23 18:07:56 +000023#include "llvm/CodeGen/Passes.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000024#include "llvm/IR/Constants.h"
Benjamin Kramer390c33c2016-01-27 16:53:42 +000025#include "llvm/IR/DIBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000028#include "llvm/IR/Function.h"
Benjamin Kramer390c33c2016-01-27 16:53:42 +000029#include "llvm/IR/IRBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000030#include "llvm/IR/InstIterator.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/IntrinsicInst.h"
33#include "llvm/IR/Intrinsics.h"
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +000034#include "llvm/IR/MDBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000035#include "llvm/IR/Module.h"
36#include "llvm/Pass.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/Format.h"
40#include "llvm/Support/MathExtras.h"
41#include "llvm/Support/raw_os_ostream.h"
Evgeniy Stepanova2002b02015-09-23 18:07:56 +000042#include "llvm/Target/TargetLowering.h"
43#include "llvm/Target/TargetSubtargetInfo.h"
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000045#include "llvm/Transforms/Utils/Local.h"
46#include "llvm/Transforms/Utils/ModuleUtils.h"
47
48using namespace llvm;
49
50#define DEBUG_TYPE "safestack"
51
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +000052enum UnsafeStackPtrStorageVal { ThreadLocalUSP, SingleThreadUSP };
53
54static cl::opt<UnsafeStackPtrStorageVal> USPStorage("safe-stack-usp-storage",
55 cl::Hidden, cl::init(ThreadLocalUSP),
56 cl::desc("Type of storage for the unsafe stack pointer"),
57 cl::values(clEnumValN(ThreadLocalUSP, "thread-local",
58 "Thread-local storage"),
59 clEnumValN(SingleThreadUSP, "single-thread",
60 "Non-thread-local storage"),
61 clEnumValEnd));
62
Peter Collingbourne82437bf2015-06-15 21:07:11 +000063namespace llvm {
64
65STATISTIC(NumFunctions, "Total number of functions");
66STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
67STATISTIC(NumUnsafeStackRestorePointsFunctions,
68 "Number of functions that use setjmp or exceptions");
69
70STATISTIC(NumAllocas, "Total number of allocas");
71STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
72STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000073STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
Peter Collingbourne82437bf2015-06-15 21:07:11 +000074STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
75
76} // namespace llvm
77
78namespace {
79
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000080/// Rewrite an SCEV expression for a memory access address to an expression that
81/// represents offset from the given alloca.
82///
83/// The implementation simply replaces all mentions of the alloca with zero.
84class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000085 const Value *AllocaPtr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +000086
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000087public:
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000088 AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
89 : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
Peter Collingbourne82437bf2015-06-15 21:07:11 +000090
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000091 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000092 if (Expr->getValue() == AllocaPtr)
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000093 return SE.getZero(Expr->getType());
94 return Expr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +000095 }
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000096};
Peter Collingbourne82437bf2015-06-15 21:07:11 +000097
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000098/// The SafeStack pass splits the stack of each function into the safe
99/// stack, which is only accessed through memory safe dereferences (as
100/// determined statically), and the unsafe stack, which contains all
101/// local variables that are accessed in ways that we can't prove to
102/// be safe.
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000103class SafeStack : public FunctionPass {
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000104 const TargetMachine *TM;
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000105 const TargetLoweringBase *TL;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000106 const DataLayout *DL;
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000107 ScalarEvolution *SE;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000108
109 Type *StackPtrTy;
110 Type *IntPtrTy;
111 Type *Int32Ty;
112 Type *Int8Ty;
113
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000114 Value *UnsafeStackPtr = nullptr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000115
116 /// Unsafe stack alignment. Each stack frame must ensure that the stack is
117 /// aligned to this value. We need to re-align the unsafe stack if the
118 /// alignment of any object on the stack exceeds this value.
119 ///
120 /// 16 seems like a reasonable upper bound on the alignment of objects that we
121 /// might expect to appear on the stack on most common targets.
122 enum { StackAlignment = 16 };
123
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000124 /// \brief Build a value representing a pointer to the unsafe stack pointer.
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000125 Value *getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F);
126
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000127 /// \brief Return the value of the stack canary.
128 Value *getStackGuard(IRBuilder<> &IRB, Function &F);
129
130 /// \brief Load stack guard from the frame and check if it has changed.
131 void checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
132 AllocaInst *StackGuardSlot, Value *StackGuard);
133
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000134 /// \brief Find all static allocas, dynamic allocas, return instructions and
135 /// stack restore points (exception unwind blocks and setjmp calls) in the
136 /// given function and append them to the respective vectors.
137 void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
138 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000139 SmallVectorImpl<Argument *> &ByValArguments,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000140 SmallVectorImpl<ReturnInst *> &Returns,
141 SmallVectorImpl<Instruction *> &StackRestorePoints);
142
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000143 /// \brief Calculate the allocation size of a given alloca. Returns 0 if the
144 /// size can not be statically determined.
145 uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
146
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000147 /// \brief Allocate space for all static allocas in \p StaticAllocas,
148 /// replace allocas with pointers into the unsafe stack and generate code to
149 /// restore the stack pointer before all return instructions in \p Returns.
150 ///
151 /// \returns A pointer to the top of the unsafe stack after all unsafe static
152 /// allocas are allocated.
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000153 Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000154 ArrayRef<AllocaInst *> StaticAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000155 ArrayRef<Argument *> ByValArguments,
Anna Zakscad79942016-02-02 01:03:11 +0000156 ArrayRef<ReturnInst *> Returns,
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000157 Instruction *BasePointer,
158 AllocaInst *StackGuardSlot);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000159
160 /// \brief Generate code to restore the stack after all stack restore points
161 /// in \p StackRestorePoints.
162 ///
163 /// \returns A local variable in which to maintain the dynamic top of the
164 /// unsafe stack if needed.
165 AllocaInst *
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000166 createStackRestorePoints(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000167 ArrayRef<Instruction *> StackRestorePoints,
168 Value *StaticTop, bool NeedDynamicTop);
169
170 /// \brief Replace all allocas in \p DynamicAllocas with code to allocate
171 /// space dynamically on the unsafe stack and store the dynamic unsafe stack
172 /// top to \p DynamicTop if non-null.
173 void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
174 AllocaInst *DynamicTop,
175 ArrayRef<AllocaInst *> DynamicAllocas);
176
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000177 bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000178
179 bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000180 const Value *AllocaPtr, uint64_t AllocaSize);
181 bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
182 uint64_t AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000183
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000184public:
185 static char ID; // Pass identification, replacement for typeid.
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000186 SafeStack(const TargetMachine *TM)
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000187 : FunctionPass(ID), TM(TM), TL(nullptr), DL(nullptr) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000188 initializeSafeStackPass(*PassRegistry::getPassRegistry());
189 }
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000190 SafeStack() : SafeStack(nullptr) {}
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000191
Hans Wennborgaa15bff2015-09-10 16:49:58 +0000192 void getAnalysisUsage(AnalysisUsage &AU) const override {
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000193 AU.addRequired<ScalarEvolutionWrapperPass>();
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000194 }
195
Hans Wennborgaa15bff2015-09-10 16:49:58 +0000196 bool doInitialization(Module &M) override {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000197 DL = &M.getDataLayout();
198
199 StackPtrTy = Type::getInt8PtrTy(M.getContext());
200 IntPtrTy = DL->getIntPtrType(M.getContext());
201 Int32Ty = Type::getInt32Ty(M.getContext());
202 Int8Ty = Type::getInt8Ty(M.getContext());
203
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000204 return false;
205 }
206
Hans Wennborgaa15bff2015-09-10 16:49:58 +0000207 bool runOnFunction(Function &F) override;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000208}; // class SafeStack
209
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000210uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) {
211 uint64_t Size = DL->getTypeAllocSize(AI->getAllocatedType());
212 if (AI->isArrayAllocation()) {
213 auto C = dyn_cast<ConstantInt>(AI->getArraySize());
214 if (!C)
215 return 0;
216 Size *= C->getZExtValue();
217 }
218 return Size;
219}
220
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000221bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize,
222 const Value *AllocaPtr, uint64_t AllocaSize) {
223 AllocaOffsetRewriter Rewriter(*SE, AllocaPtr);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000224 const SCEV *Expr = Rewriter.visit(SE->getSCEV(Addr));
225
226 uint64_t BitWidth = SE->getTypeSizeInBits(Expr->getType());
227 ConstantRange AccessStartRange = SE->getUnsignedRange(Expr);
228 ConstantRange SizeRange =
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000229 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize));
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000230 ConstantRange AccessRange = AccessStartRange.add(SizeRange);
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000231 ConstantRange AllocaRange =
232 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize));
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000233 bool Safe = AllocaRange.contains(AccessRange);
234
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000235 DEBUG(dbgs() << "[SafeStack] "
236 << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
237 << *AllocaPtr << "\n"
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000238 << " Access " << *Addr << "\n"
239 << " SCEV " << *Expr
240 << " U: " << SE->getUnsignedRange(Expr)
241 << ", S: " << SE->getSignedRange(Expr) << "\n"
242 << " Range " << AccessRange << "\n"
243 << " AllocaRange " << AllocaRange << "\n"
244 << " " << (Safe ? "safe" : "unsafe") << "\n");
245
246 return Safe;
247}
248
249bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000250 const Value *AllocaPtr,
251 uint64_t AllocaSize) {
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000252 // All MemIntrinsics have destination address in Arg0 and size in Arg2.
253 if (MI->getRawDest() != U) return true;
254 const auto *Len = dyn_cast<ConstantInt>(MI->getLength());
255 // Non-constant size => unsafe. FIXME: try SCEV getRange.
256 if (!Len) return false;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000257 return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000258}
259
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000260/// Check whether a given allocation must be put on the safe
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000261/// stack or not. The function analyzes all uses of AI and checks whether it is
262/// only accessed in a memory safe way (as decided statically).
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000263bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) {
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000264 // Go through all uses of this alloca and check whether all accesses to the
265 // allocated object are statically known to be memory safe and, hence, the
266 // object can be placed on the safe stack.
267 SmallPtrSet<const Value *, 16> Visited;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000268 SmallVector<const Value *, 8> WorkList;
269 WorkList.push_back(AllocaPtr);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000270
271 // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
272 while (!WorkList.empty()) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000273 const Value *V = WorkList.pop_back_val();
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000274 for (const Use &UI : V->uses()) {
275 auto I = cast<const Instruction>(UI.getUser());
276 assert(V == UI.get());
277
278 switch (I->getOpcode()) {
279 case Instruction::Load: {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000280 if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getType()), AllocaPtr,
281 AllocaSize))
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000282 return false;
283 break;
284 }
285 case Instruction::VAArg:
286 // "va-arg" from a pointer is safe.
287 break;
288 case Instruction::Store: {
289 if (V == I->getOperand(0)) {
290 // Stored the pointer - conservatively assume it may be unsafe.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000291 DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000292 << "\n store of address: " << *I << "\n");
293 return false;
294 }
295
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000296 if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getOperand(0)->getType()),
297 AllocaPtr, AllocaSize))
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000298 return false;
299 break;
300 }
301 case Instruction::Ret: {
302 // Information leak.
303 return false;
304 }
305
306 case Instruction::Call:
307 case Instruction::Invoke: {
308 ImmutableCallSite CS(I);
309
310 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
311 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
312 II->getIntrinsicID() == Intrinsic::lifetime_end)
313 continue;
314 }
315
316 if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000317 if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
318 DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000319 << "\n unsafe memintrinsic: " << *I
320 << "\n");
321 return false;
322 }
323 continue;
324 }
325
326 // LLVM 'nocapture' attribute is only set for arguments whose address
327 // is not stored, passed around, or used in any other non-trivial way.
328 // We assume that passing a pointer to an object as a 'nocapture
329 // readnone' argument is safe.
330 // FIXME: a more precise solution would require an interprocedural
331 // analysis here, which would look at all uses of an argument inside
332 // the function being called.
333 ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
334 for (ImmutableCallSite::arg_iterator A = B; A != E; ++A)
335 if (A->get() == V)
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000336 if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) ||
337 CS.doesNotAccessMemory()))) {
338 DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000339 << "\n unsafe call: " << *I << "\n");
340 return false;
341 }
342 continue;
343 }
344
345 default:
346 if (Visited.insert(I).second)
347 WorkList.push_back(cast<const Instruction>(I));
348 }
349 }
350 }
351
352 // All uses of the alloca are safe, we can place it on the safe stack.
353 return true;
354}
355
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000356Value *SafeStack::getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F) {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000357 // Check if there is a target-specific location for the unsafe stack pointer.
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000358 if (TL)
359 if (Value *V = TL->getSafeStackPointerLocation(IRB))
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000360 return V;
361
362 // Otherwise, assume the target links with compiler-rt, which provides a
363 // thread-local variable with a magic name.
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000364 Module &M = *F.getParent();
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000365 const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
366 auto UnsafeStackPtr =
367 dyn_cast_or_null<GlobalVariable>(M.getNamedValue(UnsafeStackPtrVar));
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000368
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +0000369 bool UseTLS = USPStorage == ThreadLocalUSP;
370
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000371 if (!UnsafeStackPtr) {
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +0000372 auto TLSModel = UseTLS ?
373 GlobalValue::InitialExecTLSModel :
374 GlobalValue::NotThreadLocal;
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000375 // The global variable is not defined yet, define it ourselves.
376 // We use the initial-exec TLS model because we do not support the
377 // variable living anywhere other than in the main executable.
378 UnsafeStackPtr = new GlobalVariable(
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000379 M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +0000380 UnsafeStackPtrVar, nullptr, TLSModel);
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000381 } else {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000382 // The variable exists, check its type and attributes.
383 if (UnsafeStackPtr->getValueType() != StackPtrTy)
384 report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +0000385 if (UseTLS != UnsafeStackPtr->isThreadLocal())
386 report_fatal_error(Twine(UnsafeStackPtrVar) + " must " +
387 (UseTLS ? "" : "not ") + "be thread-local");
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000388 }
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000389 return UnsafeStackPtr;
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000390}
391
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000392Value *SafeStack::getStackGuard(IRBuilder<> &IRB, Function &F) {
393 Value *StackGuardVar = nullptr;
394 if (TL)
395 StackGuardVar = TL->getIRStackGuard(IRB);
396 if (!StackGuardVar)
397 StackGuardVar =
398 F.getParent()->getOrInsertGlobal("__stack_chk_guard", StackPtrTy);
399 return IRB.CreateLoad(StackGuardVar, "StackGuard");
400}
401
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000402void SafeStack::findInsts(Function &F,
403 SmallVectorImpl<AllocaInst *> &StaticAllocas,
404 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000405 SmallVectorImpl<Argument *> &ByValArguments,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000406 SmallVectorImpl<ReturnInst *> &Returns,
407 SmallVectorImpl<Instruction *> &StackRestorePoints) {
Nico Rieck78199512015-08-06 19:10:45 +0000408 for (Instruction &I : instructions(&F)) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000409 if (auto AI = dyn_cast<AllocaInst>(&I)) {
410 ++NumAllocas;
411
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000412 uint64_t Size = getStaticAllocaAllocationSize(AI);
413 if (IsSafeStackAlloca(AI, Size))
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000414 continue;
415
416 if (AI->isStaticAlloca()) {
417 ++NumUnsafeStaticAllocas;
418 StaticAllocas.push_back(AI);
419 } else {
420 ++NumUnsafeDynamicAllocas;
421 DynamicAllocas.push_back(AI);
422 }
423 } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
424 Returns.push_back(RI);
425 } else if (auto CI = dyn_cast<CallInst>(&I)) {
426 // setjmps require stack restore.
427 if (CI->getCalledFunction() && CI->canReturnTwice())
428 StackRestorePoints.push_back(CI);
429 } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
430 // Exception landing pads require stack restore.
431 StackRestorePoints.push_back(LP);
432 } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
433 if (II->getIntrinsicID() == Intrinsic::gcroot)
434 llvm::report_fatal_error(
435 "gcroot intrinsic not compatible with safestack attribute");
436 }
437 }
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000438 for (Argument &Arg : F.args()) {
439 if (!Arg.hasByValAttr())
440 continue;
441 uint64_t Size =
442 DL->getTypeStoreSize(Arg.getType()->getPointerElementType());
443 if (IsSafeStackAlloca(&Arg, Size))
444 continue;
445
446 ++NumUnsafeByValArguments;
447 ByValArguments.push_back(&Arg);
448 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000449}
450
451AllocaInst *
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000452SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000453 ArrayRef<Instruction *> StackRestorePoints,
454 Value *StaticTop, bool NeedDynamicTop) {
Anna Zakscad79942016-02-02 01:03:11 +0000455 assert(StaticTop && "The stack top isn't set.");
456
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000457 if (StackRestorePoints.empty())
458 return nullptr;
459
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000460 // We need the current value of the shadow stack pointer to restore
461 // after longjmp or exception catching.
462
463 // FIXME: On some platforms this could be handled by the longjmp/exception
464 // runtime itself.
465
466 AllocaInst *DynamicTop = nullptr;
Anna Zakscad79942016-02-02 01:03:11 +0000467 if (NeedDynamicTop) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000468 // If we also have dynamic alloca's, the stack pointer value changes
469 // throughout the function. For now we store it in an alloca.
470 DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
471 "unsafe_stack_dynamic_ptr");
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000472 IRB.CreateStore(StaticTop, DynamicTop);
Anna Zakscad79942016-02-02 01:03:11 +0000473 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000474
475 // Restore current stack pointer after longjmp/exception catch.
476 for (Instruction *I : StackRestorePoints) {
477 ++NumUnsafeStackRestorePoints;
478
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000479 IRB.SetInsertPoint(I->getNextNode());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000480 Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
481 IRB.CreateStore(CurrentTop, UnsafeStackPtr);
482 }
483
484 return DynamicTop;
485}
486
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000487void SafeStack::checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
488 AllocaInst *StackGuardSlot, Value *StackGuard) {
489 Value *V = IRB.CreateLoad(StackGuardSlot);
490 Value *Cmp = IRB.CreateICmpNE(StackGuard, V);
491
492 auto SuccessProb = BranchProbabilityInfo::getBranchProbStackProtector(true);
493 auto FailureProb = BranchProbabilityInfo::getBranchProbStackProtector(false);
494 MDNode *Weights = MDBuilder(F.getContext())
495 .createBranchWeights(SuccessProb.getNumerator(),
496 FailureProb.getNumerator());
497 Instruction *CheckTerm =
498 SplitBlockAndInsertIfThen(Cmp, &RI,
499 /* Unreachable */ true, Weights);
500 IRBuilder<> IRBFail(CheckTerm);
501 // FIXME: respect -fsanitize-trap / -ftrap-function here?
502 Constant *StackChkFail = F.getParent()->getOrInsertFunction(
503 "__stack_chk_fail", IRB.getVoidTy(), nullptr);
504 IRBFail.CreateCall(StackChkFail, {});
505}
506
Anna Zakscad79942016-02-02 01:03:11 +0000507/// We explicitly compute and set the unsafe stack layout for all unsafe
508/// static alloca instructions. We save the unsafe "base pointer" in the
509/// prologue into a local variable and restore it in the epilogue.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000510Value *SafeStack::moveStaticAllocasToUnsafeStack(
511 IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
Anna Zakscad79942016-02-02 01:03:11 +0000512 ArrayRef<Argument *> ByValArguments, ArrayRef<ReturnInst *> Returns,
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000513 Instruction *BasePointer, AllocaInst *StackGuardSlot) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000514 if (StaticAllocas.empty() && ByValArguments.empty())
Anna Zakscad79942016-02-02 01:03:11 +0000515 return BasePointer;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000516
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000517 DIBuilder DIB(*F.getParent());
518
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000519 // Compute maximum alignment among static objects on the unsafe stack.
520 unsigned MaxAlignment = 0;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000521 for (Argument *Arg : ByValArguments) {
522 Type *Ty = Arg->getType()->getPointerElementType();
523 unsigned Align = std::max((unsigned)DL->getPrefTypeAlignment(Ty),
524 Arg->getParamAlignment());
525 if (Align > MaxAlignment)
526 MaxAlignment = Align;
527 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000528 for (AllocaInst *AI : StaticAllocas) {
529 Type *Ty = AI->getAllocatedType();
530 unsigned Align =
531 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
532 if (Align > MaxAlignment)
533 MaxAlignment = Align;
534 }
535
536 if (MaxAlignment > StackAlignment) {
537 // Re-align the base pointer according to the max requested alignment.
538 assert(isPowerOf2_32(MaxAlignment));
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000539 IRB.SetInsertPoint(BasePointer->getNextNode());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000540 BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
541 IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
542 ConstantInt::get(IntPtrTy, ~uint64_t(MaxAlignment - 1))),
543 StackPtrTy));
544 }
545
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000546 int64_t StaticOffset = 0; // Current stack top.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000547 IRB.SetInsertPoint(BasePointer->getNextNode());
548
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000549 if (StackGuardSlot) {
550 StaticOffset += getStaticAllocaAllocationSize(StackGuardSlot);
551 Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
552 ConstantInt::get(Int32Ty, -StaticOffset));
553 Value *NewAI =
554 IRB.CreateBitCast(Off, StackGuardSlot->getType(), "StackGuardSlot");
555
556 // Replace alloc with the new location.
557 StackGuardSlot->replaceAllUsesWith(NewAI);
558 StackGuardSlot->eraseFromParent();
559 }
560
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000561 for (Argument *Arg : ByValArguments) {
562 Type *Ty = Arg->getType()->getPointerElementType();
563
564 uint64_t Size = DL->getTypeStoreSize(Ty);
565 if (Size == 0)
566 Size = 1; // Don't create zero-sized stack objects.
567
568 // Ensure the object is properly aligned.
569 unsigned Align = std::max((unsigned)DL->getPrefTypeAlignment(Ty),
570 Arg->getParamAlignment());
571
572 // Add alignment.
573 // NOTE: we ensure that BasePointer itself is aligned to >= Align.
574 StaticOffset += Size;
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000575 StaticOffset = alignTo(StaticOffset, Align);
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000576
577 Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
578 ConstantInt::get(Int32Ty, -StaticOffset));
579 Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
580 Arg->getName() + ".unsafe-byval");
581
582 // Replace alloc with the new location.
583 replaceDbgDeclare(Arg, BasePointer, BasePointer->getNextNode(), DIB,
584 /*Deref=*/true, -StaticOffset);
585 Arg->replaceAllUsesWith(NewArg);
586 IRB.SetInsertPoint(cast<Instruction>(NewArg)->getNextNode());
587 IRB.CreateMemCpy(Off, Arg, Size, Arg->getParamAlignment());
588 }
589
590 // Allocate space for every unsafe static AllocaInst on the unsafe stack.
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000591 for (AllocaInst *AI : StaticAllocas) {
592 IRB.SetInsertPoint(AI);
593
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000594 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000595 uint64_t Size = getStaticAllocaAllocationSize(AI);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000596 if (Size == 0)
597 Size = 1; // Don't create zero-sized stack objects.
598
599 // Ensure the object is properly aligned.
600 unsigned Align =
601 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
602
603 // Add alignment.
604 // NOTE: we ensure that BasePointer itself is aligned to >= Align.
605 StaticOffset += Size;
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000606 StaticOffset = alignTo(StaticOffset, Align);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000607
Evgeniy Stepanovf6081112015-09-30 19:55:43 +0000608 replaceDbgDeclareForAlloca(AI, BasePointer, DIB, /*Deref=*/true, -StaticOffset);
Evgeniy Stepanov72d961a2016-06-16 22:34:00 +0000609 replaceDbgValueForAlloca(AI, BasePointer, DIB, -StaticOffset);
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000610
611 // Replace uses of the alloca with the new location.
612 // Insert address calculation close to each use to work around PR27844.
613 std::string Name = std::string(AI->getName()) + ".unsafe";
614 while (!AI->use_empty()) {
615 Use &U = *AI->use_begin();
616 Instruction *User = cast<Instruction>(U.getUser());
617
618 Instruction *InsertBefore;
619 if (auto *PHI = dyn_cast<PHINode>(User))
620 InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
621 else
622 InsertBefore = User;
623
624 IRBuilder<> IRBUser(InsertBefore);
625 Value *Off = IRBUser.CreateGEP(BasePointer, // BasePointer is i8*
626 ConstantInt::get(Int32Ty, -StaticOffset));
627 Value *Replacement = IRBUser.CreateBitCast(Off, AI->getType(), Name);
628
629 if (auto *PHI = dyn_cast<PHINode>(User)) {
630 // PHI nodes may have multiple incoming edges from the same BB (why??),
631 // all must be updated at once with the same incoming value.
632 auto *BB = PHI->getIncomingBlock(U);
633 for (unsigned I = 0; I < PHI->getNumIncomingValues(); ++I)
634 if (PHI->getIncomingBlock(I) == BB)
635 PHI->setIncomingValue(I, Replacement);
636 } else {
637 U.set(Replacement);
638 }
639 }
640
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000641 AI->eraseFromParent();
642 }
643
644 // Re-align BasePointer so that our callees would see it aligned as
645 // expected.
646 // FIXME: no need to update BasePointer in leaf functions.
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000647 StaticOffset = alignTo(StaticOffset, StackAlignment);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000648
649 // Update shadow stack pointer in the function epilogue.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000650 IRB.SetInsertPoint(BasePointer->getNextNode());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000651
652 Value *StaticTop =
653 IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -StaticOffset),
654 "unsafe_stack_static_top");
655 IRB.CreateStore(StaticTop, UnsafeStackPtr);
656 return StaticTop;
657}
658
659void SafeStack::moveDynamicAllocasToUnsafeStack(
660 Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
661 ArrayRef<AllocaInst *> DynamicAllocas) {
662 DIBuilder DIB(*F.getParent());
663
664 for (AllocaInst *AI : DynamicAllocas) {
665 IRBuilder<> IRB(AI);
666
667 // Compute the new SP value (after AI).
668 Value *ArraySize = AI->getArraySize();
669 if (ArraySize->getType() != IntPtrTy)
670 ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
671
672 Type *Ty = AI->getAllocatedType();
673 uint64_t TySize = DL->getTypeAllocSize(Ty);
674 Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
675
676 Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy);
677 SP = IRB.CreateSub(SP, Size);
678
679 // Align the SP value to satisfy the AllocaInst, type and stack alignments.
680 unsigned Align = std::max(
681 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()),
682 (unsigned)StackAlignment);
683
684 assert(isPowerOf2_32(Align));
685 Value *NewTop = IRB.CreateIntToPtr(
686 IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
687 StackPtrTy);
688
689 // Save the stack pointer.
690 IRB.CreateStore(NewTop, UnsafeStackPtr);
691 if (DynamicTop)
692 IRB.CreateStore(NewTop, DynamicTop);
693
Evgeniy Stepanov9842d612015-11-25 22:52:30 +0000694 Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000695 if (AI->hasName() && isa<Instruction>(NewAI))
696 NewAI->takeName(AI);
697
698 replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true);
699 AI->replaceAllUsesWith(NewAI);
700 AI->eraseFromParent();
701 }
702
703 if (!DynamicAllocas.empty()) {
704 // Now go through the instructions again, replacing stacksave/stackrestore.
705 for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
706 Instruction *I = &*(It++);
707 auto II = dyn_cast<IntrinsicInst>(I);
708 if (!II)
709 continue;
710
711 if (II->getIntrinsicID() == Intrinsic::stacksave) {
712 IRBuilder<> IRB(II);
713 Instruction *LI = IRB.CreateLoad(UnsafeStackPtr);
714 LI->takeName(II);
715 II->replaceAllUsesWith(LI);
716 II->eraseFromParent();
717 } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
718 IRBuilder<> IRB(II);
719 Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
720 SI->takeName(II);
721 assert(II->use_empty());
722 II->eraseFromParent();
723 }
724 }
725 }
726}
727
728bool SafeStack::runOnFunction(Function &F) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000729 DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
730
731 if (!F.hasFnAttribute(Attribute::SafeStack)) {
732 DEBUG(dbgs() << "[SafeStack] safestack is not requested"
733 " for this function\n");
734 return false;
735 }
736
737 if (F.isDeclaration()) {
738 DEBUG(dbgs() << "[SafeStack] function definition"
739 " is not available\n");
740 return false;
741 }
742
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000743 TL = TM ? TM->getSubtargetImpl(F)->getTargetLowering() : nullptr;
744 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000745
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000746 ++NumFunctions;
747
748 SmallVector<AllocaInst *, 16> StaticAllocas;
749 SmallVector<AllocaInst *, 4> DynamicAllocas;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000750 SmallVector<Argument *, 4> ByValArguments;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000751 SmallVector<ReturnInst *, 4> Returns;
752
753 // Collect all points where stack gets unwound and needs to be restored
754 // This is only necessary because the runtime (setjmp and unwind code) is
755 // not aware of the unsafe stack and won't unwind/restore it prorerly.
756 // To work around this problem without changing the runtime, we insert
757 // instrumentation to restore the unsafe stack pointer when necessary.
758 SmallVector<Instruction *, 4> StackRestorePoints;
759
760 // Find all static and dynamic alloca instructions that must be moved to the
761 // unsafe stack, all return instructions and stack restore points.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000762 findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
763 StackRestorePoints);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000764
765 if (StaticAllocas.empty() && DynamicAllocas.empty() &&
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000766 ByValArguments.empty() && StackRestorePoints.empty())
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000767 return false; // Nothing to do in this function.
768
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000769 if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
770 !ByValArguments.empty())
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000771 ++NumUnsafeStackFunctions; // This function has the unsafe stack.
772
773 if (!StackRestorePoints.empty())
774 ++NumUnsafeStackRestorePointsFunctions;
775
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000776 IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000777 UnsafeStackPtr = getOrCreateUnsafeStackPtr(IRB, F);
Peter Collingbournede26a912015-06-22 20:26:54 +0000778
Anna Zakscad79942016-02-02 01:03:11 +0000779 // Load the current stack pointer (we'll also use it as a base pointer).
780 // FIXME: use a dedicated register for it ?
781 Instruction *BasePointer =
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000782 IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
Anna Zakscad79942016-02-02 01:03:11 +0000783 assert(BasePointer->getType() == StackPtrTy);
784
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000785 AllocaInst *StackGuardSlot = nullptr;
786 // FIXME: implement weaker forms of stack protector.
787 if (F.hasFnAttribute(Attribute::StackProtect) ||
788 F.hasFnAttribute(Attribute::StackProtectStrong) ||
789 F.hasFnAttribute(Attribute::StackProtectReq)) {
790 Value *StackGuard = getStackGuard(IRB, F);
791 StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr);
792 IRB.CreateStore(StackGuard, StackGuardSlot);
793
794 for (ReturnInst *RI : Returns) {
795 IRBuilder<> IRBRet(RI);
796 checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
797 }
798 }
799
800 // The top of the unsafe stack after all unsafe static allocas are
801 // allocated.
802 Value *StaticTop =
803 moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, ByValArguments,
804 Returns, BasePointer, StackGuardSlot);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000805
806 // Safe stack object that stores the current unsafe stack top. It is updated
807 // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
808 // This is only needed if we need to restore stack pointer after longjmp
809 // or exceptions, and we have dynamic allocations.
810 // FIXME: a better alternative might be to store the unsafe stack pointer
811 // before setjmp / invoke instructions.
812 AllocaInst *DynamicTop = createStackRestorePoints(
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000813 IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000814
815 // Handle dynamic allocas.
816 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
817 DynamicAllocas);
818
Anna Zakscad79942016-02-02 01:03:11 +0000819 // Restore the unsafe stack pointer before each return.
820 for (ReturnInst *RI : Returns) {
821 IRB.SetInsertPoint(RI);
822 IRB.CreateStore(BasePointer, UnsafeStackPtr);
823 }
824
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000825 DEBUG(dbgs() << "[SafeStack] safestack applied\n");
826 return true;
827}
828
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000829} // anonymous namespace
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000830
831char SafeStack::ID = 0;
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000832INITIALIZE_TM_PASS_BEGIN(SafeStack, "safe-stack",
833 "Safe Stack instrumentation pass", false, false)
834INITIALIZE_TM_PASS_END(SafeStack, "safe-stack",
835 "Safe Stack instrumentation pass", false, false)
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000836
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000837FunctionPass *llvm::createSafeStackPass(const llvm::TargetMachine *TM) {
838 return new SafeStack(TM);
839}