blob: 1a6635f571426b9232fc5a82173d06db6ea83075 [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"
Benjamin Kramer390c33c2016-01-27 16:53:42 +000024#include "llvm/CodeGen/Passes.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000025#include "llvm/IR/Constants.h"
Benjamin Kramer390c33c2016-01-27 16:53:42 +000026#include "llvm/IR/DIBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000027#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000029#include "llvm/IR/Function.h"
Benjamin Kramer390c33c2016-01-27 16:53:42 +000030#include "llvm/IR/IRBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000031#include "llvm/IR/InstIterator.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Intrinsics.h"
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +000035#include "llvm/IR/MDBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000036#include "llvm/IR/Module.h"
37#include "llvm/Pass.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/Format.h"
41#include "llvm/Support/MathExtras.h"
42#include "llvm/Support/raw_os_ostream.h"
Evgeniy Stepanova2002b02015-09-23 18:07:56 +000043#include "llvm/Target/TargetLowering.h"
44#include "llvm/Target/TargetSubtargetInfo.h"
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000046#include "llvm/Transforms/Utils/Local.h"
47#include "llvm/Transforms/Utils/ModuleUtils.h"
48
49using namespace llvm;
50
51#define DEBUG_TYPE "safestack"
52
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +000053enum UnsafeStackPtrStorageVal { ThreadLocalUSP, SingleThreadUSP };
54
55static cl::opt<UnsafeStackPtrStorageVal> USPStorage("safe-stack-usp-storage",
56 cl::Hidden, cl::init(ThreadLocalUSP),
57 cl::desc("Type of storage for the unsafe stack pointer"),
58 cl::values(clEnumValN(ThreadLocalUSP, "thread-local",
59 "Thread-local storage"),
60 clEnumValN(SingleThreadUSP, "single-thread",
61 "Non-thread-local storage"),
62 clEnumValEnd));
63
Peter Collingbourne82437bf2015-06-15 21:07:11 +000064namespace llvm {
65
66STATISTIC(NumFunctions, "Total number of functions");
67STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
68STATISTIC(NumUnsafeStackRestorePointsFunctions,
69 "Number of functions that use setjmp or exceptions");
70
71STATISTIC(NumAllocas, "Total number of allocas");
72STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
73STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000074STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
Peter Collingbourne82437bf2015-06-15 21:07:11 +000075STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
76
77} // namespace llvm
78
79namespace {
80
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000081/// Rewrite an SCEV expression for a memory access address to an expression that
82/// represents offset from the given alloca.
83///
84/// The implementation simply replaces all mentions of the alloca with zero.
85class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000086 const Value *AllocaPtr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +000087
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000088public:
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000089 AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
90 : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
Peter Collingbourne82437bf2015-06-15 21:07:11 +000091
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000092 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000093 if (Expr->getValue() == AllocaPtr)
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000094 return SE.getZero(Expr->getType());
95 return Expr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +000096 }
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000097};
Peter Collingbourne82437bf2015-06-15 21:07:11 +000098
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000099/// The SafeStack pass splits the stack of each function into the safe
100/// stack, which is only accessed through memory safe dereferences (as
101/// determined statically), and the unsafe stack, which contains all
102/// local variables that are accessed in ways that we can't prove to
103/// be safe.
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000104class SafeStack : public FunctionPass {
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000105 const TargetMachine *TM;
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000106 const TargetLoweringBase *TL;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000107 const DataLayout *DL;
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000108 ScalarEvolution *SE;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000109
110 Type *StackPtrTy;
111 Type *IntPtrTy;
112 Type *Int32Ty;
113 Type *Int8Ty;
114
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000115 Value *UnsafeStackPtr = nullptr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000116
117 /// Unsafe stack alignment. Each stack frame must ensure that the stack is
118 /// aligned to this value. We need to re-align the unsafe stack if the
119 /// alignment of any object on the stack exceeds this value.
120 ///
121 /// 16 seems like a reasonable upper bound on the alignment of objects that we
122 /// might expect to appear on the stack on most common targets.
123 enum { StackAlignment = 16 };
124
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000125 /// \brief Build a value representing a pointer to the unsafe stack pointer.
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000126 Value *getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F);
127
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000128 /// \brief Return the value of the stack canary.
129 Value *getStackGuard(IRBuilder<> &IRB, Function &F);
130
131 /// \brief Load stack guard from the frame and check if it has changed.
132 void checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
133 AllocaInst *StackGuardSlot, Value *StackGuard);
134
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000135 /// \brief Find all static allocas, dynamic allocas, return instructions and
136 /// stack restore points (exception unwind blocks and setjmp calls) in the
137 /// given function and append them to the respective vectors.
138 void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
139 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000140 SmallVectorImpl<Argument *> &ByValArguments,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000141 SmallVectorImpl<ReturnInst *> &Returns,
142 SmallVectorImpl<Instruction *> &StackRestorePoints);
143
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000144 /// \brief Calculate the allocation size of a given alloca. Returns 0 if the
145 /// size can not be statically determined.
146 uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
147
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000148 /// \brief Allocate space for all static allocas in \p StaticAllocas,
149 /// replace allocas with pointers into the unsafe stack and generate code to
150 /// restore the stack pointer before all return instructions in \p Returns.
151 ///
152 /// \returns A pointer to the top of the unsafe stack after all unsafe static
153 /// allocas are allocated.
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000154 Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000155 ArrayRef<AllocaInst *> StaticAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000156 ArrayRef<Argument *> ByValArguments,
Anna Zakscad79942016-02-02 01:03:11 +0000157 ArrayRef<ReturnInst *> Returns,
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000158 Instruction *BasePointer,
159 AllocaInst *StackGuardSlot);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000160
161 /// \brief Generate code to restore the stack after all stack restore points
162 /// in \p StackRestorePoints.
163 ///
164 /// \returns A local variable in which to maintain the dynamic top of the
165 /// unsafe stack if needed.
166 AllocaInst *
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000167 createStackRestorePoints(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000168 ArrayRef<Instruction *> StackRestorePoints,
169 Value *StaticTop, bool NeedDynamicTop);
170
171 /// \brief Replace all allocas in \p DynamicAllocas with code to allocate
172 /// space dynamically on the unsafe stack and store the dynamic unsafe stack
173 /// top to \p DynamicTop if non-null.
174 void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
175 AllocaInst *DynamicTop,
176 ArrayRef<AllocaInst *> DynamicAllocas);
177
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000178 bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000179
180 bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000181 const Value *AllocaPtr, uint64_t AllocaSize);
182 bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
183 uint64_t AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000184
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000185public:
186 static char ID; // Pass identification, replacement for typeid.
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000187 SafeStack(const TargetMachine *TM)
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000188 : FunctionPass(ID), TM(TM), TL(nullptr), DL(nullptr) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000189 initializeSafeStackPass(*PassRegistry::getPassRegistry());
190 }
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000191 SafeStack() : SafeStack(nullptr) {}
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000192
Hans Wennborgaa15bff2015-09-10 16:49:58 +0000193 void getAnalysisUsage(AnalysisUsage &AU) const override {
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000194 AU.addRequired<ScalarEvolutionWrapperPass>();
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000195 }
196
Hans Wennborgaa15bff2015-09-10 16:49:58 +0000197 bool doInitialization(Module &M) override {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000198 DL = &M.getDataLayout();
199
200 StackPtrTy = Type::getInt8PtrTy(M.getContext());
201 IntPtrTy = DL->getIntPtrType(M.getContext());
202 Int32Ty = Type::getInt32Ty(M.getContext());
203 Int8Ty = Type::getInt8Ty(M.getContext());
204
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000205 return false;
206 }
207
Hans Wennborgaa15bff2015-09-10 16:49:58 +0000208 bool runOnFunction(Function &F) override;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000209}; // class SafeStack
210
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000211uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) {
212 uint64_t Size = DL->getTypeAllocSize(AI->getAllocatedType());
213 if (AI->isArrayAllocation()) {
214 auto C = dyn_cast<ConstantInt>(AI->getArraySize());
215 if (!C)
216 return 0;
217 Size *= C->getZExtValue();
218 }
219 return Size;
220}
221
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000222bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize,
223 const Value *AllocaPtr, uint64_t AllocaSize) {
224 AllocaOffsetRewriter Rewriter(*SE, AllocaPtr);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000225 const SCEV *Expr = Rewriter.visit(SE->getSCEV(Addr));
226
227 uint64_t BitWidth = SE->getTypeSizeInBits(Expr->getType());
228 ConstantRange AccessStartRange = SE->getUnsignedRange(Expr);
229 ConstantRange SizeRange =
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000230 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize));
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000231 ConstantRange AccessRange = AccessStartRange.add(SizeRange);
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000232 ConstantRange AllocaRange =
233 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize));
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000234 bool Safe = AllocaRange.contains(AccessRange);
235
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000236 DEBUG(dbgs() << "[SafeStack] "
237 << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
238 << *AllocaPtr << "\n"
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000239 << " Access " << *Addr << "\n"
240 << " SCEV " << *Expr
241 << " U: " << SE->getUnsignedRange(Expr)
242 << ", S: " << SE->getSignedRange(Expr) << "\n"
243 << " Range " << AccessRange << "\n"
244 << " AllocaRange " << AllocaRange << "\n"
245 << " " << (Safe ? "safe" : "unsafe") << "\n");
246
247 return Safe;
248}
249
250bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000251 const Value *AllocaPtr,
252 uint64_t AllocaSize) {
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000253 // All MemIntrinsics have destination address in Arg0 and size in Arg2.
254 if (MI->getRawDest() != U) return true;
255 const auto *Len = dyn_cast<ConstantInt>(MI->getLength());
256 // Non-constant size => unsafe. FIXME: try SCEV getRange.
257 if (!Len) return false;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000258 return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000259}
260
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000261/// Check whether a given allocation must be put on the safe
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000262/// stack or not. The function analyzes all uses of AI and checks whether it is
263/// only accessed in a memory safe way (as decided statically).
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000264bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) {
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000265 // Go through all uses of this alloca and check whether all accesses to the
266 // allocated object are statically known to be memory safe and, hence, the
267 // object can be placed on the safe stack.
268 SmallPtrSet<const Value *, 16> Visited;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000269 SmallVector<const Value *, 8> WorkList;
270 WorkList.push_back(AllocaPtr);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000271
272 // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
273 while (!WorkList.empty()) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000274 const Value *V = WorkList.pop_back_val();
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000275 for (const Use &UI : V->uses()) {
276 auto I = cast<const Instruction>(UI.getUser());
277 assert(V == UI.get());
278
279 switch (I->getOpcode()) {
280 case Instruction::Load: {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000281 if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getType()), AllocaPtr,
282 AllocaSize))
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000283 return false;
284 break;
285 }
286 case Instruction::VAArg:
287 // "va-arg" from a pointer is safe.
288 break;
289 case Instruction::Store: {
290 if (V == I->getOperand(0)) {
291 // Stored the pointer - conservatively assume it may be unsafe.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000292 DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000293 << "\n store of address: " << *I << "\n");
294 return false;
295 }
296
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000297 if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getOperand(0)->getType()),
298 AllocaPtr, AllocaSize))
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000299 return false;
300 break;
301 }
302 case Instruction::Ret: {
303 // Information leak.
304 return false;
305 }
306
307 case Instruction::Call:
308 case Instruction::Invoke: {
309 ImmutableCallSite CS(I);
310
311 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
312 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
313 II->getIntrinsicID() == Intrinsic::lifetime_end)
314 continue;
315 }
316
317 if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000318 if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
319 DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000320 << "\n unsafe memintrinsic: " << *I
321 << "\n");
322 return false;
323 }
324 continue;
325 }
326
327 // LLVM 'nocapture' attribute is only set for arguments whose address
328 // is not stored, passed around, or used in any other non-trivial way.
329 // We assume that passing a pointer to an object as a 'nocapture
330 // readnone' argument is safe.
331 // FIXME: a more precise solution would require an interprocedural
332 // analysis here, which would look at all uses of an argument inside
333 // the function being called.
334 ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
335 for (ImmutableCallSite::arg_iterator A = B; A != E; ++A)
336 if (A->get() == V)
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000337 if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) ||
338 CS.doesNotAccessMemory()))) {
339 DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000340 << "\n unsafe call: " << *I << "\n");
341 return false;
342 }
343 continue;
344 }
345
346 default:
347 if (Visited.insert(I).second)
348 WorkList.push_back(cast<const Instruction>(I));
349 }
350 }
351 }
352
353 // All uses of the alloca are safe, we can place it on the safe stack.
354 return true;
355}
356
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000357Value *SafeStack::getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F) {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000358 // Check if there is a target-specific location for the unsafe stack pointer.
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000359 if (TL)
360 if (Value *V = TL->getSafeStackPointerLocation(IRB))
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000361 return V;
362
363 // Otherwise, assume the target links with compiler-rt, which provides a
364 // thread-local variable with a magic name.
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000365 Module &M = *F.getParent();
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000366 const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
367 auto UnsafeStackPtr =
368 dyn_cast_or_null<GlobalVariable>(M.getNamedValue(UnsafeStackPtrVar));
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000369
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +0000370 bool UseTLS = USPStorage == ThreadLocalUSP;
371
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000372 if (!UnsafeStackPtr) {
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +0000373 auto TLSModel = UseTLS ?
374 GlobalValue::InitialExecTLSModel :
375 GlobalValue::NotThreadLocal;
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000376 // The global variable is not defined yet, define it ourselves.
377 // We use the initial-exec TLS model because we do not support the
378 // variable living anywhere other than in the main executable.
379 UnsafeStackPtr = new GlobalVariable(
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000380 M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +0000381 UnsafeStackPtrVar, nullptr, TLSModel);
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000382 } else {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000383 // The variable exists, check its type and attributes.
384 if (UnsafeStackPtr->getValueType() != StackPtrTy)
385 report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +0000386 if (UseTLS != UnsafeStackPtr->isThreadLocal())
387 report_fatal_error(Twine(UnsafeStackPtrVar) + " must " +
388 (UseTLS ? "" : "not ") + "be thread-local");
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000389 }
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000390 return UnsafeStackPtr;
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000391}
392
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000393Value *SafeStack::getStackGuard(IRBuilder<> &IRB, Function &F) {
394 Value *StackGuardVar = nullptr;
395 if (TL)
396 StackGuardVar = TL->getIRStackGuard(IRB);
397 if (!StackGuardVar)
398 StackGuardVar =
399 F.getParent()->getOrInsertGlobal("__stack_chk_guard", StackPtrTy);
400 return IRB.CreateLoad(StackGuardVar, "StackGuard");
401}
402
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000403void SafeStack::findInsts(Function &F,
404 SmallVectorImpl<AllocaInst *> &StaticAllocas,
405 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000406 SmallVectorImpl<Argument *> &ByValArguments,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000407 SmallVectorImpl<ReturnInst *> &Returns,
408 SmallVectorImpl<Instruction *> &StackRestorePoints) {
Nico Rieck78199512015-08-06 19:10:45 +0000409 for (Instruction &I : instructions(&F)) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000410 if (auto AI = dyn_cast<AllocaInst>(&I)) {
411 ++NumAllocas;
412
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000413 uint64_t Size = getStaticAllocaAllocationSize(AI);
414 if (IsSafeStackAlloca(AI, Size))
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000415 continue;
416
417 if (AI->isStaticAlloca()) {
418 ++NumUnsafeStaticAllocas;
419 StaticAllocas.push_back(AI);
420 } else {
421 ++NumUnsafeDynamicAllocas;
422 DynamicAllocas.push_back(AI);
423 }
424 } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
425 Returns.push_back(RI);
426 } else if (auto CI = dyn_cast<CallInst>(&I)) {
427 // setjmps require stack restore.
428 if (CI->getCalledFunction() && CI->canReturnTwice())
429 StackRestorePoints.push_back(CI);
430 } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
431 // Exception landing pads require stack restore.
432 StackRestorePoints.push_back(LP);
433 } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
434 if (II->getIntrinsicID() == Intrinsic::gcroot)
435 llvm::report_fatal_error(
436 "gcroot intrinsic not compatible with safestack attribute");
437 }
438 }
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000439 for (Argument &Arg : F.args()) {
440 if (!Arg.hasByValAttr())
441 continue;
442 uint64_t Size =
443 DL->getTypeStoreSize(Arg.getType()->getPointerElementType());
444 if (IsSafeStackAlloca(&Arg, Size))
445 continue;
446
447 ++NumUnsafeByValArguments;
448 ByValArguments.push_back(&Arg);
449 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000450}
451
452AllocaInst *
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000453SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000454 ArrayRef<Instruction *> StackRestorePoints,
455 Value *StaticTop, bool NeedDynamicTop) {
Anna Zakscad79942016-02-02 01:03:11 +0000456 assert(StaticTop && "The stack top isn't set.");
457
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000458 if (StackRestorePoints.empty())
459 return nullptr;
460
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000461 // We need the current value of the shadow stack pointer to restore
462 // after longjmp or exception catching.
463
464 // FIXME: On some platforms this could be handled by the longjmp/exception
465 // runtime itself.
466
467 AllocaInst *DynamicTop = nullptr;
Anna Zakscad79942016-02-02 01:03:11 +0000468 if (NeedDynamicTop) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000469 // If we also have dynamic alloca's, the stack pointer value changes
470 // throughout the function. For now we store it in an alloca.
471 DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
472 "unsafe_stack_dynamic_ptr");
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000473 IRB.CreateStore(StaticTop, DynamicTop);
Anna Zakscad79942016-02-02 01:03:11 +0000474 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000475
476 // Restore current stack pointer after longjmp/exception catch.
477 for (Instruction *I : StackRestorePoints) {
478 ++NumUnsafeStackRestorePoints;
479
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000480 IRB.SetInsertPoint(I->getNextNode());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000481 Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
482 IRB.CreateStore(CurrentTop, UnsafeStackPtr);
483 }
484
485 return DynamicTop;
486}
487
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000488void SafeStack::checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
489 AllocaInst *StackGuardSlot, Value *StackGuard) {
490 Value *V = IRB.CreateLoad(StackGuardSlot);
491 Value *Cmp = IRB.CreateICmpNE(StackGuard, V);
492
493 auto SuccessProb = BranchProbabilityInfo::getBranchProbStackProtector(true);
494 auto FailureProb = BranchProbabilityInfo::getBranchProbStackProtector(false);
495 MDNode *Weights = MDBuilder(F.getContext())
496 .createBranchWeights(SuccessProb.getNumerator(),
497 FailureProb.getNumerator());
498 Instruction *CheckTerm =
499 SplitBlockAndInsertIfThen(Cmp, &RI,
500 /* Unreachable */ true, Weights);
501 IRBuilder<> IRBFail(CheckTerm);
502 // FIXME: respect -fsanitize-trap / -ftrap-function here?
503 Constant *StackChkFail = F.getParent()->getOrInsertFunction(
504 "__stack_chk_fail", IRB.getVoidTy(), nullptr);
505 IRBFail.CreateCall(StackChkFail, {});
506}
507
Anna Zakscad79942016-02-02 01:03:11 +0000508/// We explicitly compute and set the unsafe stack layout for all unsafe
509/// static alloca instructions. We save the unsafe "base pointer" in the
510/// prologue into a local variable and restore it in the epilogue.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000511Value *SafeStack::moveStaticAllocasToUnsafeStack(
512 IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
Anna Zakscad79942016-02-02 01:03:11 +0000513 ArrayRef<Argument *> ByValArguments, ArrayRef<ReturnInst *> Returns,
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000514 Instruction *BasePointer, AllocaInst *StackGuardSlot) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000515 if (StaticAllocas.empty() && ByValArguments.empty())
Anna Zakscad79942016-02-02 01:03:11 +0000516 return BasePointer;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000517
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000518 DIBuilder DIB(*F.getParent());
519
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000520 // Compute maximum alignment among static objects on the unsafe stack.
521 unsigned MaxAlignment = 0;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000522 for (Argument *Arg : ByValArguments) {
523 Type *Ty = Arg->getType()->getPointerElementType();
524 unsigned Align = std::max((unsigned)DL->getPrefTypeAlignment(Ty),
525 Arg->getParamAlignment());
526 if (Align > MaxAlignment)
527 MaxAlignment = Align;
528 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000529 for (AllocaInst *AI : StaticAllocas) {
530 Type *Ty = AI->getAllocatedType();
531 unsigned Align =
532 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
533 if (Align > MaxAlignment)
534 MaxAlignment = Align;
535 }
536
537 if (MaxAlignment > StackAlignment) {
538 // Re-align the base pointer according to the max requested alignment.
539 assert(isPowerOf2_32(MaxAlignment));
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000540 IRB.SetInsertPoint(BasePointer->getNextNode());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000541 BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
542 IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
543 ConstantInt::get(IntPtrTy, ~uint64_t(MaxAlignment - 1))),
544 StackPtrTy));
545 }
546
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000547 int64_t StaticOffset = 0; // Current stack top.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000548 IRB.SetInsertPoint(BasePointer->getNextNode());
549
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000550 if (StackGuardSlot) {
551 StaticOffset += getStaticAllocaAllocationSize(StackGuardSlot);
552 Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
553 ConstantInt::get(Int32Ty, -StaticOffset));
554 Value *NewAI =
555 IRB.CreateBitCast(Off, StackGuardSlot->getType(), "StackGuardSlot");
556
557 // Replace alloc with the new location.
558 StackGuardSlot->replaceAllUsesWith(NewAI);
559 StackGuardSlot->eraseFromParent();
560 }
561
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000562 for (Argument *Arg : ByValArguments) {
563 Type *Ty = Arg->getType()->getPointerElementType();
564
565 uint64_t Size = DL->getTypeStoreSize(Ty);
566 if (Size == 0)
567 Size = 1; // Don't create zero-sized stack objects.
568
569 // Ensure the object is properly aligned.
570 unsigned Align = std::max((unsigned)DL->getPrefTypeAlignment(Ty),
571 Arg->getParamAlignment());
572
573 // Add alignment.
574 // NOTE: we ensure that BasePointer itself is aligned to >= Align.
575 StaticOffset += Size;
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000576 StaticOffset = alignTo(StaticOffset, Align);
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000577
578 Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
579 ConstantInt::get(Int32Ty, -StaticOffset));
580 Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
581 Arg->getName() + ".unsafe-byval");
582
583 // Replace alloc with the new location.
584 replaceDbgDeclare(Arg, BasePointer, BasePointer->getNextNode(), DIB,
585 /*Deref=*/true, -StaticOffset);
586 Arg->replaceAllUsesWith(NewArg);
587 IRB.SetInsertPoint(cast<Instruction>(NewArg)->getNextNode());
588 IRB.CreateMemCpy(Off, Arg, Size, Arg->getParamAlignment());
589 }
590
591 // Allocate space for every unsafe static AllocaInst on the unsafe stack.
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000592 for (AllocaInst *AI : StaticAllocas) {
593 IRB.SetInsertPoint(AI);
594
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000595 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000596 uint64_t Size = getStaticAllocaAllocationSize(AI);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000597 if (Size == 0)
598 Size = 1; // Don't create zero-sized stack objects.
599
600 // Ensure the object is properly aligned.
601 unsigned Align =
602 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
603
604 // Add alignment.
605 // NOTE: we ensure that BasePointer itself is aligned to >= Align.
606 StaticOffset += Size;
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000607 StaticOffset = alignTo(StaticOffset, Align);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000608
609 Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
610 ConstantInt::get(Int32Ty, -StaticOffset));
611 Value *NewAI = IRB.CreateBitCast(Off, AI->getType(), AI->getName());
612 if (AI->hasName() && isa<Instruction>(NewAI))
613 cast<Instruction>(NewAI)->takeName(AI);
614
615 // Replace alloc with the new location.
Evgeniy Stepanovf6081112015-09-30 19:55:43 +0000616 replaceDbgDeclareForAlloca(AI, BasePointer, DIB, /*Deref=*/true, -StaticOffset);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000617 AI->replaceAllUsesWith(NewAI);
618 AI->eraseFromParent();
619 }
620
621 // Re-align BasePointer so that our callees would see it aligned as
622 // expected.
623 // FIXME: no need to update BasePointer in leaf functions.
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000624 StaticOffset = alignTo(StaticOffset, StackAlignment);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000625
626 // Update shadow stack pointer in the function epilogue.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000627 IRB.SetInsertPoint(BasePointer->getNextNode());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000628
629 Value *StaticTop =
630 IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -StaticOffset),
631 "unsafe_stack_static_top");
632 IRB.CreateStore(StaticTop, UnsafeStackPtr);
633 return StaticTop;
634}
635
636void SafeStack::moveDynamicAllocasToUnsafeStack(
637 Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
638 ArrayRef<AllocaInst *> DynamicAllocas) {
639 DIBuilder DIB(*F.getParent());
640
641 for (AllocaInst *AI : DynamicAllocas) {
642 IRBuilder<> IRB(AI);
643
644 // Compute the new SP value (after AI).
645 Value *ArraySize = AI->getArraySize();
646 if (ArraySize->getType() != IntPtrTy)
647 ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
648
649 Type *Ty = AI->getAllocatedType();
650 uint64_t TySize = DL->getTypeAllocSize(Ty);
651 Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
652
653 Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy);
654 SP = IRB.CreateSub(SP, Size);
655
656 // Align the SP value to satisfy the AllocaInst, type and stack alignments.
657 unsigned Align = std::max(
658 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()),
659 (unsigned)StackAlignment);
660
661 assert(isPowerOf2_32(Align));
662 Value *NewTop = IRB.CreateIntToPtr(
663 IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
664 StackPtrTy);
665
666 // Save the stack pointer.
667 IRB.CreateStore(NewTop, UnsafeStackPtr);
668 if (DynamicTop)
669 IRB.CreateStore(NewTop, DynamicTop);
670
Evgeniy Stepanov9842d612015-11-25 22:52:30 +0000671 Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000672 if (AI->hasName() && isa<Instruction>(NewAI))
673 NewAI->takeName(AI);
674
675 replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true);
676 AI->replaceAllUsesWith(NewAI);
677 AI->eraseFromParent();
678 }
679
680 if (!DynamicAllocas.empty()) {
681 // Now go through the instructions again, replacing stacksave/stackrestore.
682 for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
683 Instruction *I = &*(It++);
684 auto II = dyn_cast<IntrinsicInst>(I);
685 if (!II)
686 continue;
687
688 if (II->getIntrinsicID() == Intrinsic::stacksave) {
689 IRBuilder<> IRB(II);
690 Instruction *LI = IRB.CreateLoad(UnsafeStackPtr);
691 LI->takeName(II);
692 II->replaceAllUsesWith(LI);
693 II->eraseFromParent();
694 } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
695 IRBuilder<> IRB(II);
696 Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
697 SI->takeName(II);
698 assert(II->use_empty());
699 II->eraseFromParent();
700 }
701 }
702 }
703}
704
705bool SafeStack::runOnFunction(Function &F) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000706 DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
707
708 if (!F.hasFnAttribute(Attribute::SafeStack)) {
709 DEBUG(dbgs() << "[SafeStack] safestack is not requested"
710 " for this function\n");
711 return false;
712 }
713
714 if (F.isDeclaration()) {
715 DEBUG(dbgs() << "[SafeStack] function definition"
716 " is not available\n");
717 return false;
718 }
719
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000720 TL = TM ? TM->getSubtargetImpl(F)->getTargetLowering() : nullptr;
721 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000722
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000723 ++NumFunctions;
724
725 SmallVector<AllocaInst *, 16> StaticAllocas;
726 SmallVector<AllocaInst *, 4> DynamicAllocas;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000727 SmallVector<Argument *, 4> ByValArguments;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000728 SmallVector<ReturnInst *, 4> Returns;
729
730 // Collect all points where stack gets unwound and needs to be restored
731 // This is only necessary because the runtime (setjmp and unwind code) is
732 // not aware of the unsafe stack and won't unwind/restore it prorerly.
733 // To work around this problem without changing the runtime, we insert
734 // instrumentation to restore the unsafe stack pointer when necessary.
735 SmallVector<Instruction *, 4> StackRestorePoints;
736
737 // Find all static and dynamic alloca instructions that must be moved to the
738 // unsafe stack, all return instructions and stack restore points.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000739 findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
740 StackRestorePoints);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000741
742 if (StaticAllocas.empty() && DynamicAllocas.empty() &&
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000743 ByValArguments.empty() && StackRestorePoints.empty())
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000744 return false; // Nothing to do in this function.
745
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000746 if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
747 !ByValArguments.empty())
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000748 ++NumUnsafeStackFunctions; // This function has the unsafe stack.
749
750 if (!StackRestorePoints.empty())
751 ++NumUnsafeStackRestorePointsFunctions;
752
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000753 IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000754 UnsafeStackPtr = getOrCreateUnsafeStackPtr(IRB, F);
Peter Collingbournede26a912015-06-22 20:26:54 +0000755
Anna Zakscad79942016-02-02 01:03:11 +0000756 // Load the current stack pointer (we'll also use it as a base pointer).
757 // FIXME: use a dedicated register for it ?
758 Instruction *BasePointer =
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000759 IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
Anna Zakscad79942016-02-02 01:03:11 +0000760 assert(BasePointer->getType() == StackPtrTy);
761
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000762 AllocaInst *StackGuardSlot = nullptr;
763 // FIXME: implement weaker forms of stack protector.
764 if (F.hasFnAttribute(Attribute::StackProtect) ||
765 F.hasFnAttribute(Attribute::StackProtectStrong) ||
766 F.hasFnAttribute(Attribute::StackProtectReq)) {
767 Value *StackGuard = getStackGuard(IRB, F);
768 StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr);
769 IRB.CreateStore(StackGuard, StackGuardSlot);
770
771 for (ReturnInst *RI : Returns) {
772 IRBuilder<> IRBRet(RI);
773 checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
774 }
775 }
776
777 // The top of the unsafe stack after all unsafe static allocas are
778 // allocated.
779 Value *StaticTop =
780 moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, ByValArguments,
781 Returns, BasePointer, StackGuardSlot);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000782
783 // Safe stack object that stores the current unsafe stack top. It is updated
784 // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
785 // This is only needed if we need to restore stack pointer after longjmp
786 // or exceptions, and we have dynamic allocations.
787 // FIXME: a better alternative might be to store the unsafe stack pointer
788 // before setjmp / invoke instructions.
789 AllocaInst *DynamicTop = createStackRestorePoints(
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000790 IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000791
792 // Handle dynamic allocas.
793 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
794 DynamicAllocas);
795
Anna Zakscad79942016-02-02 01:03:11 +0000796 // Restore the unsafe stack pointer before each return.
797 for (ReturnInst *RI : Returns) {
798 IRB.SetInsertPoint(RI);
799 IRB.CreateStore(BasePointer, UnsafeStackPtr);
800 }
801
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000802 DEBUG(dbgs() << "[SafeStack] safestack applied\n");
803 return true;
804}
805
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000806} // anonymous namespace
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000807
808char SafeStack::ID = 0;
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000809INITIALIZE_TM_PASS_BEGIN(SafeStack, "safe-stack",
810 "Safe Stack instrumentation pass", false, false)
811INITIALIZE_TM_PASS_END(SafeStack, "safe-stack",
812 "Safe Stack instrumentation pass", false, false)
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000813
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000814FunctionPass *llvm::createSafeStackPass(const llvm::TargetMachine *TM) {
815 return new SafeStack(TM);
816}