blob: 2f934f5ae02adb342218e89d6dff76e21f6057b1 [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
Evgeniy Stepanova5da2562016-06-29 20:37:43 +000018#include "SafeStackColoring.h"
19#include "SafeStackLayout.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000020#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/Triple.h"
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +000022#include "llvm/Analysis/BranchProbabilityInfo.h"
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000023#include "llvm/Analysis/ScalarEvolution.h"
24#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Evgeniy Stepanova2002b02015-09-23 18:07:56 +000025#include "llvm/CodeGen/Passes.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000026#include "llvm/IR/Constants.h"
Benjamin Kramer390c33c2016-01-27 16:53:42 +000027#include "llvm/IR/DIBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DerivedTypes.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000030#include "llvm/IR/Function.h"
Benjamin Kramer390c33c2016-01-27 16:53:42 +000031#include "llvm/IR/IRBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000032#include "llvm/IR/InstIterator.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/Intrinsics.h"
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +000036#include "llvm/IR/MDBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000037#include "llvm/IR/Module.h"
38#include "llvm/Pass.h"
39#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/Debug.h"
41#include "llvm/Support/Format.h"
42#include "llvm/Support/MathExtras.h"
43#include "llvm/Support/raw_os_ostream.h"
Evgeniy Stepanova2002b02015-09-23 18:07:56 +000044#include "llvm/Target/TargetLowering.h"
45#include "llvm/Target/TargetSubtargetInfo.h"
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000047#include "llvm/Transforms/Utils/Local.h"
48#include "llvm/Transforms/Utils/ModuleUtils.h"
49
50using namespace llvm;
Evgeniy Stepanova5da2562016-06-29 20:37:43 +000051using namespace llvm::safestack;
Peter Collingbourne82437bf2015-06-15 21:07:11 +000052
53#define DEBUG_TYPE "safestack"
54
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +000055enum UnsafeStackPtrStorageVal { ThreadLocalUSP, SingleThreadUSP };
56
57static cl::opt<UnsafeStackPtrStorageVal> USPStorage("safe-stack-usp-storage",
58 cl::Hidden, cl::init(ThreadLocalUSP),
59 cl::desc("Type of storage for the unsafe stack pointer"),
60 cl::values(clEnumValN(ThreadLocalUSP, "thread-local",
61 "Thread-local storage"),
62 clEnumValN(SingleThreadUSP, "single-thread",
Mehdi Amini732afdd2016-10-08 19:41:06 +000063 "Non-thread-local storage")));
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +000064
Peter Collingbourne82437bf2015-06-15 21:07:11 +000065namespace llvm {
66
67STATISTIC(NumFunctions, "Total number of functions");
68STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
69STATISTIC(NumUnsafeStackRestorePointsFunctions,
70 "Number of functions that use setjmp or exceptions");
71
72STATISTIC(NumAllocas, "Total number of allocas");
73STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
74STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000075STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
Peter Collingbourne82437bf2015-06-15 21:07:11 +000076STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
77
78} // namespace llvm
79
80namespace {
81
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000082/// Rewrite an SCEV expression for a memory access address to an expression that
83/// represents offset from the given alloca.
84///
85/// The implementation simply replaces all mentions of the alloca with zero.
86class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000087 const Value *AllocaPtr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +000088
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000089public:
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000090 AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
91 : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
Peter Collingbourne82437bf2015-06-15 21:07:11 +000092
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000093 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000094 if (Expr->getValue() == AllocaPtr)
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000095 return SE.getZero(Expr->getType());
96 return Expr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +000097 }
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000098};
Peter Collingbourne82437bf2015-06-15 21:07:11 +000099
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000100/// The SafeStack pass splits the stack of each function into the safe
101/// stack, which is only accessed through memory safe dereferences (as
102/// determined statically), and the unsafe stack, which contains all
103/// local variables that are accessed in ways that we can't prove to
104/// be safe.
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000105class SafeStack : public FunctionPass {
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000106 const TargetMachine *TM;
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000107 const TargetLoweringBase *TL;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000108 const DataLayout *DL;
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000109 ScalarEvolution *SE;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000110
111 Type *StackPtrTy;
112 Type *IntPtrTy;
113 Type *Int32Ty;
114 Type *Int8Ty;
115
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000116 Value *UnsafeStackPtr = nullptr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000117
118 /// Unsafe stack alignment. Each stack frame must ensure that the stack is
119 /// aligned to this value. We need to re-align the unsafe stack if the
120 /// alignment of any object on the stack exceeds this value.
121 ///
122 /// 16 seems like a reasonable upper bound on the alignment of objects that we
123 /// might expect to appear on the stack on most common targets.
124 enum { StackAlignment = 16 };
125
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000126 /// \brief Build a value representing a pointer to the unsafe stack pointer.
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000127 Value *getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F);
128
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000129 /// \brief Return the value of the stack canary.
130 Value *getStackGuard(IRBuilder<> &IRB, Function &F);
131
132 /// \brief Load stack guard from the frame and check if it has changed.
133 void checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
134 AllocaInst *StackGuardSlot, Value *StackGuard);
135
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000136 /// \brief Find all static allocas, dynamic allocas, return instructions and
137 /// stack restore points (exception unwind blocks and setjmp calls) in the
138 /// given function and append them to the respective vectors.
139 void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
140 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000141 SmallVectorImpl<Argument *> &ByValArguments,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000142 SmallVectorImpl<ReturnInst *> &Returns,
143 SmallVectorImpl<Instruction *> &StackRestorePoints);
144
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000145 /// \brief Calculate the allocation size of a given alloca. Returns 0 if the
146 /// size can not be statically determined.
147 uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
148
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000149 /// \brief Allocate space for all static allocas in \p StaticAllocas,
150 /// replace allocas with pointers into the unsafe stack and generate code to
151 /// restore the stack pointer before all return instructions in \p Returns.
152 ///
153 /// \returns A pointer to the top of the unsafe stack after all unsafe static
154 /// allocas are allocated.
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000155 Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000156 ArrayRef<AllocaInst *> StaticAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000157 ArrayRef<Argument *> ByValArguments,
Anna Zakscad79942016-02-02 01:03:11 +0000158 ArrayRef<ReturnInst *> Returns,
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000159 Instruction *BasePointer,
160 AllocaInst *StackGuardSlot);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000161
162 /// \brief Generate code to restore the stack after all stack restore points
163 /// in \p StackRestorePoints.
164 ///
165 /// \returns A local variable in which to maintain the dynamic top of the
166 /// unsafe stack if needed.
167 AllocaInst *
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000168 createStackRestorePoints(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000169 ArrayRef<Instruction *> StackRestorePoints,
170 Value *StaticTop, bool NeedDynamicTop);
171
172 /// \brief Replace all allocas in \p DynamicAllocas with code to allocate
173 /// space dynamically on the unsafe stack and store the dynamic unsafe stack
174 /// top to \p DynamicTop if non-null.
175 void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
176 AllocaInst *DynamicTop,
177 ArrayRef<AllocaInst *> DynamicAllocas);
178
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000179 bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000180
181 bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000182 const Value *AllocaPtr, uint64_t AllocaSize);
183 bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
184 uint64_t AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000185
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000186public:
187 static char ID; // Pass identification, replacement for typeid.
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000188 SafeStack(const TargetMachine *TM)
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000189 : FunctionPass(ID), TM(TM), TL(nullptr), DL(nullptr) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000190 initializeSafeStackPass(*PassRegistry::getPassRegistry());
191 }
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000192 SafeStack() : SafeStack(nullptr) {}
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000193
Hans Wennborgaa15bff2015-09-10 16:49:58 +0000194 void getAnalysisUsage(AnalysisUsage &AU) const override {
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000195 AU.addRequired<ScalarEvolutionWrapperPass>();
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000196 }
197
Hans Wennborgaa15bff2015-09-10 16:49:58 +0000198 bool doInitialization(Module &M) override {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000199 DL = &M.getDataLayout();
200
201 StackPtrTy = Type::getInt8PtrTy(M.getContext());
202 IntPtrTy = DL->getIntPtrType(M.getContext());
203 Int32Ty = Type::getInt32Ty(M.getContext());
204 Int8Ty = Type::getInt8Ty(M.getContext());
205
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000206 return false;
207 }
208
Hans Wennborgaa15bff2015-09-10 16:49:58 +0000209 bool runOnFunction(Function &F) override;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000210}; // class SafeStack
211
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000212uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) {
213 uint64_t Size = DL->getTypeAllocSize(AI->getAllocatedType());
214 if (AI->isArrayAllocation()) {
215 auto C = dyn_cast<ConstantInt>(AI->getArraySize());
216 if (!C)
217 return 0;
218 Size *= C->getZExtValue();
219 }
220 return Size;
221}
222
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000223bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize,
224 const Value *AllocaPtr, uint64_t AllocaSize) {
225 AllocaOffsetRewriter Rewriter(*SE, AllocaPtr);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000226 const SCEV *Expr = Rewriter.visit(SE->getSCEV(Addr));
227
228 uint64_t BitWidth = SE->getTypeSizeInBits(Expr->getType());
229 ConstantRange AccessStartRange = SE->getUnsignedRange(Expr);
230 ConstantRange SizeRange =
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000231 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize));
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000232 ConstantRange AccessRange = AccessStartRange.add(SizeRange);
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000233 ConstantRange AllocaRange =
234 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize));
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000235 bool Safe = AllocaRange.contains(AccessRange);
236
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000237 DEBUG(dbgs() << "[SafeStack] "
238 << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
239 << *AllocaPtr << "\n"
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000240 << " Access " << *Addr << "\n"
241 << " SCEV " << *Expr
242 << " U: " << SE->getUnsignedRange(Expr)
243 << ", S: " << SE->getSignedRange(Expr) << "\n"
244 << " Range " << AccessRange << "\n"
245 << " AllocaRange " << AllocaRange << "\n"
246 << " " << (Safe ? "safe" : "unsafe") << "\n");
247
248 return Safe;
249}
250
251bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000252 const Value *AllocaPtr,
253 uint64_t AllocaSize) {
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000254 // All MemIntrinsics have destination address in Arg0 and size in Arg2.
255 if (MI->getRawDest() != U) return true;
256 const auto *Len = dyn_cast<ConstantInt>(MI->getLength());
257 // Non-constant size => unsafe. FIXME: try SCEV getRange.
258 if (!Len) return false;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000259 return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000260}
261
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000262/// Check whether a given allocation must be put on the safe
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000263/// stack or not. The function analyzes all uses of AI and checks whether it is
264/// only accessed in a memory safe way (as decided statically).
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000265bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) {
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000266 // Go through all uses of this alloca and check whether all accesses to the
267 // allocated object are statically known to be memory safe and, hence, the
268 // object can be placed on the safe stack.
269 SmallPtrSet<const Value *, 16> Visited;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000270 SmallVector<const Value *, 8> WorkList;
271 WorkList.push_back(AllocaPtr);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000272
273 // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
274 while (!WorkList.empty()) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000275 const Value *V = WorkList.pop_back_val();
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000276 for (const Use &UI : V->uses()) {
277 auto I = cast<const Instruction>(UI.getUser());
278 assert(V == UI.get());
279
280 switch (I->getOpcode()) {
281 case Instruction::Load: {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000282 if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getType()), AllocaPtr,
283 AllocaSize))
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000284 return false;
285 break;
286 }
287 case Instruction::VAArg:
288 // "va-arg" from a pointer is safe.
289 break;
290 case Instruction::Store: {
291 if (V == I->getOperand(0)) {
292 // Stored the pointer - conservatively assume it may be unsafe.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000293 DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000294 << "\n store of address: " << *I << "\n");
295 return false;
296 }
297
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000298 if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getOperand(0)->getType()),
299 AllocaPtr, AllocaSize))
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000300 return false;
301 break;
302 }
303 case Instruction::Ret: {
304 // Information leak.
305 return false;
306 }
307
308 case Instruction::Call:
309 case Instruction::Invoke: {
310 ImmutableCallSite CS(I);
311
312 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
313 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
314 II->getIntrinsicID() == Intrinsic::lifetime_end)
315 continue;
316 }
317
318 if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000319 if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
320 DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000321 << "\n unsafe memintrinsic: " << *I
322 << "\n");
323 return false;
324 }
325 continue;
326 }
327
328 // LLVM 'nocapture' attribute is only set for arguments whose address
329 // is not stored, passed around, or used in any other non-trivial way.
330 // We assume that passing a pointer to an object as a 'nocapture
331 // readnone' argument is safe.
332 // FIXME: a more precise solution would require an interprocedural
333 // analysis here, which would look at all uses of an argument inside
334 // the function being called.
335 ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
336 for (ImmutableCallSite::arg_iterator A = B; A != E; ++A)
337 if (A->get() == V)
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000338 if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) ||
339 CS.doesNotAccessMemory()))) {
340 DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000341 << "\n unsafe call: " << *I << "\n");
342 return false;
343 }
344 continue;
345 }
346
347 default:
348 if (Visited.insert(I).second)
349 WorkList.push_back(cast<const Instruction>(I));
350 }
351 }
352 }
353
354 // All uses of the alloca are safe, we can place it on the safe stack.
355 return true;
356}
357
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000358Value *SafeStack::getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F) {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000359 // Check if there is a target-specific location for the unsafe stack pointer.
David L Kreitzer7c7ee892016-10-04 20:57:19 +0000360 if (TL)
361 if (Value *V = TL->getSafeStackPointerLocation(IRB))
362 return V;
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000363
364 // Otherwise, assume the target links with compiler-rt, which provides a
365 // thread-local variable with a magic name.
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000366 Module &M = *F.getParent();
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000367 const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
368 auto UnsafeStackPtr =
369 dyn_cast_or_null<GlobalVariable>(M.getNamedValue(UnsafeStackPtrVar));
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000370
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +0000371 bool UseTLS = USPStorage == ThreadLocalUSP;
372
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000373 if (!UnsafeStackPtr) {
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +0000374 auto TLSModel = UseTLS ?
375 GlobalValue::InitialExecTLSModel :
376 GlobalValue::NotThreadLocal;
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000377 // The global variable is not defined yet, define it ourselves.
378 // We use the initial-exec TLS model because we do not support the
379 // variable living anywhere other than in the main executable.
380 UnsafeStackPtr = new GlobalVariable(
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000381 M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +0000382 UnsafeStackPtrVar, nullptr, TLSModel);
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000383 } else {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000384 // The variable exists, check its type and attributes.
385 if (UnsafeStackPtr->getValueType() != StackPtrTy)
386 report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
Evgeniy Stepanov8827f2d2015-12-22 00:13:11 +0000387 if (UseTLS != UnsafeStackPtr->isThreadLocal())
388 report_fatal_error(Twine(UnsafeStackPtrVar) + " must " +
389 (UseTLS ? "" : "not ") + "be thread-local");
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000390 }
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000391 return UnsafeStackPtr;
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000392}
393
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000394Value *SafeStack::getStackGuard(IRBuilder<> &IRB, Function &F) {
David L Kreitzer7c7ee892016-10-04 20:57:19 +0000395 Value *StackGuardVar = nullptr;
396 if (TL)
397 StackGuardVar = TL->getIRStackGuard(IRB);
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000398 if (!StackGuardVar)
399 StackGuardVar =
400 F.getParent()->getOrInsertGlobal("__stack_chk_guard", StackPtrTy);
401 return IRB.CreateLoad(StackGuardVar, "StackGuard");
402}
403
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000404void SafeStack::findInsts(Function &F,
405 SmallVectorImpl<AllocaInst *> &StaticAllocas,
406 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000407 SmallVectorImpl<Argument *> &ByValArguments,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000408 SmallVectorImpl<ReturnInst *> &Returns,
409 SmallVectorImpl<Instruction *> &StackRestorePoints) {
Nico Rieck78199512015-08-06 19:10:45 +0000410 for (Instruction &I : instructions(&F)) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000411 if (auto AI = dyn_cast<AllocaInst>(&I)) {
412 ++NumAllocas;
413
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000414 uint64_t Size = getStaticAllocaAllocationSize(AI);
415 if (IsSafeStackAlloca(AI, Size))
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000416 continue;
417
418 if (AI->isStaticAlloca()) {
419 ++NumUnsafeStaticAllocas;
420 StaticAllocas.push_back(AI);
421 } else {
422 ++NumUnsafeDynamicAllocas;
423 DynamicAllocas.push_back(AI);
424 }
425 } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
426 Returns.push_back(RI);
427 } else if (auto CI = dyn_cast<CallInst>(&I)) {
428 // setjmps require stack restore.
429 if (CI->getCalledFunction() && CI->canReturnTwice())
430 StackRestorePoints.push_back(CI);
431 } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
432 // Exception landing pads require stack restore.
433 StackRestorePoints.push_back(LP);
434 } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
435 if (II->getIntrinsicID() == Intrinsic::gcroot)
436 llvm::report_fatal_error(
437 "gcroot intrinsic not compatible with safestack attribute");
438 }
439 }
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000440 for (Argument &Arg : F.args()) {
441 if (!Arg.hasByValAttr())
442 continue;
443 uint64_t Size =
444 DL->getTypeStoreSize(Arg.getType()->getPointerElementType());
445 if (IsSafeStackAlloca(&Arg, Size))
446 continue;
447
448 ++NumUnsafeByValArguments;
449 ByValArguments.push_back(&Arg);
450 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000451}
452
453AllocaInst *
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000454SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000455 ArrayRef<Instruction *> StackRestorePoints,
456 Value *StaticTop, bool NeedDynamicTop) {
Anna Zakscad79942016-02-02 01:03:11 +0000457 assert(StaticTop && "The stack top isn't set.");
458
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000459 if (StackRestorePoints.empty())
460 return nullptr;
461
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000462 // We need the current value of the shadow stack pointer to restore
463 // after longjmp or exception catching.
464
465 // FIXME: On some platforms this could be handled by the longjmp/exception
466 // runtime itself.
467
468 AllocaInst *DynamicTop = nullptr;
Anna Zakscad79942016-02-02 01:03:11 +0000469 if (NeedDynamicTop) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000470 // If we also have dynamic alloca's, the stack pointer value changes
471 // throughout the function. For now we store it in an alloca.
472 DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
473 "unsafe_stack_dynamic_ptr");
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000474 IRB.CreateStore(StaticTop, DynamicTop);
Anna Zakscad79942016-02-02 01:03:11 +0000475 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000476
477 // Restore current stack pointer after longjmp/exception catch.
478 for (Instruction *I : StackRestorePoints) {
479 ++NumUnsafeStackRestorePoints;
480
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000481 IRB.SetInsertPoint(I->getNextNode());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000482 Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
483 IRB.CreateStore(CurrentTop, UnsafeStackPtr);
484 }
485
486 return DynamicTop;
487}
488
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000489void SafeStack::checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
490 AllocaInst *StackGuardSlot, Value *StackGuard) {
491 Value *V = IRB.CreateLoad(StackGuardSlot);
492 Value *Cmp = IRB.CreateICmpNE(StackGuard, V);
493
494 auto SuccessProb = BranchProbabilityInfo::getBranchProbStackProtector(true);
495 auto FailureProb = BranchProbabilityInfo::getBranchProbStackProtector(false);
496 MDNode *Weights = MDBuilder(F.getContext())
497 .createBranchWeights(SuccessProb.getNumerator(),
498 FailureProb.getNumerator());
499 Instruction *CheckTerm =
500 SplitBlockAndInsertIfThen(Cmp, &RI,
501 /* Unreachable */ true, Weights);
502 IRBuilder<> IRBFail(CheckTerm);
503 // FIXME: respect -fsanitize-trap / -ftrap-function here?
504 Constant *StackChkFail = F.getParent()->getOrInsertFunction(
505 "__stack_chk_fail", IRB.getVoidTy(), nullptr);
506 IRBFail.CreateCall(StackChkFail, {});
507}
508
Anna Zakscad79942016-02-02 01:03:11 +0000509/// We explicitly compute and set the unsafe stack layout for all unsafe
510/// static alloca instructions. We save the unsafe "base pointer" in the
511/// prologue into a local variable and restore it in the epilogue.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000512Value *SafeStack::moveStaticAllocasToUnsafeStack(
513 IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
Anna Zakscad79942016-02-02 01:03:11 +0000514 ArrayRef<Argument *> ByValArguments, ArrayRef<ReturnInst *> Returns,
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000515 Instruction *BasePointer, AllocaInst *StackGuardSlot) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000516 if (StaticAllocas.empty() && ByValArguments.empty())
Anna Zakscad79942016-02-02 01:03:11 +0000517 return BasePointer;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000518
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000519 DIBuilder DIB(*F.getParent());
520
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000521 StackColoring SSC(F, StaticAllocas);
522 SSC.run();
523 SSC.removeAllMarkers();
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000524
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000525 // Unsafe stack always grows down.
526 StackLayout SSL(StackAlignment);
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000527 if (StackGuardSlot) {
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000528 Type *Ty = StackGuardSlot->getAllocatedType();
529 unsigned Align =
530 std::max(DL->getPrefTypeAlignment(Ty), StackGuardSlot->getAlignment());
531 SSL.addObject(StackGuardSlot, getStaticAllocaAllocationSize(StackGuardSlot),
Evgeniy Stepanov906f6fb2016-07-26 00:05:14 +0000532 Align, SSC.getFullLiveRange());
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000533 }
534
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000535 for (Argument *Arg : ByValArguments) {
536 Type *Ty = Arg->getType()->getPointerElementType();
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000537 uint64_t Size = DL->getTypeStoreSize(Ty);
538 if (Size == 0)
539 Size = 1; // Don't create zero-sized stack objects.
540
541 // Ensure the object is properly aligned.
542 unsigned Align = std::max((unsigned)DL->getPrefTypeAlignment(Ty),
543 Arg->getParamAlignment());
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000544 SSL.addObject(Arg, Size, Align, SSC.getFullLiveRange());
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000545 }
546
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000547 for (AllocaInst *AI : StaticAllocas) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000548 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000549 uint64_t Size = getStaticAllocaAllocationSize(AI);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000550 if (Size == 0)
551 Size = 1; // Don't create zero-sized stack objects.
552
553 // Ensure the object is properly aligned.
554 unsigned Align =
555 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
556
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000557 SSL.addObject(AI, Size, Align, SSC.getLiveRange(AI));
558 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000559
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000560 SSL.computeLayout();
561 unsigned FrameAlignment = SSL.getFrameAlignment();
562
563 // FIXME: tell SSL that we start at a less-then-MaxAlignment aligned location
564 // (AlignmentSkew).
565 if (FrameAlignment > StackAlignment) {
566 // Re-align the base pointer according to the max requested alignment.
567 assert(isPowerOf2_32(FrameAlignment));
568 IRB.SetInsertPoint(BasePointer->getNextNode());
569 BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
570 IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
571 ConstantInt::get(IntPtrTy, ~uint64_t(FrameAlignment - 1))),
572 StackPtrTy));
573 }
574
575 IRB.SetInsertPoint(BasePointer->getNextNode());
576
577 if (StackGuardSlot) {
578 unsigned Offset = SSL.getObjectOffset(StackGuardSlot);
579 Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
580 ConstantInt::get(Int32Ty, -Offset));
581 Value *NewAI =
582 IRB.CreateBitCast(Off, StackGuardSlot->getType(), "StackGuardSlot");
583
584 // Replace alloc with the new location.
585 StackGuardSlot->replaceAllUsesWith(NewAI);
586 StackGuardSlot->eraseFromParent();
587 }
588
589 for (Argument *Arg : ByValArguments) {
590 unsigned Offset = SSL.getObjectOffset(Arg);
591 Type *Ty = Arg->getType()->getPointerElementType();
592
593 uint64_t Size = DL->getTypeStoreSize(Ty);
594 if (Size == 0)
595 Size = 1; // Don't create zero-sized stack objects.
596
597 Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
598 ConstantInt::get(Int32Ty, -Offset));
599 Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
600 Arg->getName() + ".unsafe-byval");
601
602 // Replace alloc with the new location.
603 replaceDbgDeclare(Arg, BasePointer, BasePointer->getNextNode(), DIB,
604 /*Deref=*/true, -Offset);
605 Arg->replaceAllUsesWith(NewArg);
606 IRB.SetInsertPoint(cast<Instruction>(NewArg)->getNextNode());
607 IRB.CreateMemCpy(Off, Arg, Size, Arg->getParamAlignment());
608 }
609
610 // Allocate space for every unsafe static AllocaInst on the unsafe stack.
611 for (AllocaInst *AI : StaticAllocas) {
612 IRB.SetInsertPoint(AI);
613 unsigned Offset = SSL.getObjectOffset(AI);
614
615 uint64_t Size = getStaticAllocaAllocationSize(AI);
616 if (Size == 0)
617 Size = 1; // Don't create zero-sized stack objects.
618
619 replaceDbgDeclareForAlloca(AI, BasePointer, DIB, /*Deref=*/true, -Offset);
620 replaceDbgValueForAlloca(AI, BasePointer, DIB, -Offset);
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000621
622 // Replace uses of the alloca with the new location.
623 // Insert address calculation close to each use to work around PR27844.
624 std::string Name = std::string(AI->getName()) + ".unsafe";
625 while (!AI->use_empty()) {
626 Use &U = *AI->use_begin();
627 Instruction *User = cast<Instruction>(U.getUser());
628
629 Instruction *InsertBefore;
630 if (auto *PHI = dyn_cast<PHINode>(User))
631 InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
632 else
633 InsertBefore = User;
634
635 IRBuilder<> IRBUser(InsertBefore);
636 Value *Off = IRBUser.CreateGEP(BasePointer, // BasePointer is i8*
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000637 ConstantInt::get(Int32Ty, -Offset));
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000638 Value *Replacement = IRBUser.CreateBitCast(Off, AI->getType(), Name);
639
640 if (auto *PHI = dyn_cast<PHINode>(User)) {
641 // PHI nodes may have multiple incoming edges from the same BB (why??),
642 // all must be updated at once with the same incoming value.
643 auto *BB = PHI->getIncomingBlock(U);
644 for (unsigned I = 0; I < PHI->getNumIncomingValues(); ++I)
645 if (PHI->getIncomingBlock(I) == BB)
646 PHI->setIncomingValue(I, Replacement);
647 } else {
648 U.set(Replacement);
649 }
650 }
651
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000652 AI->eraseFromParent();
653 }
654
655 // Re-align BasePointer so that our callees would see it aligned as
656 // expected.
657 // FIXME: no need to update BasePointer in leaf functions.
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000658 unsigned FrameSize = alignTo(SSL.getFrameSize(), StackAlignment);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000659
660 // Update shadow stack pointer in the function epilogue.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000661 IRB.SetInsertPoint(BasePointer->getNextNode());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000662
663 Value *StaticTop =
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000664 IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -FrameSize),
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000665 "unsafe_stack_static_top");
666 IRB.CreateStore(StaticTop, UnsafeStackPtr);
667 return StaticTop;
668}
669
670void SafeStack::moveDynamicAllocasToUnsafeStack(
671 Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
672 ArrayRef<AllocaInst *> DynamicAllocas) {
673 DIBuilder DIB(*F.getParent());
674
675 for (AllocaInst *AI : DynamicAllocas) {
676 IRBuilder<> IRB(AI);
677
678 // Compute the new SP value (after AI).
679 Value *ArraySize = AI->getArraySize();
680 if (ArraySize->getType() != IntPtrTy)
681 ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
682
683 Type *Ty = AI->getAllocatedType();
684 uint64_t TySize = DL->getTypeAllocSize(Ty);
685 Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
686
687 Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy);
688 SP = IRB.CreateSub(SP, Size);
689
690 // Align the SP value to satisfy the AllocaInst, type and stack alignments.
691 unsigned Align = std::max(
692 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()),
693 (unsigned)StackAlignment);
694
695 assert(isPowerOf2_32(Align));
696 Value *NewTop = IRB.CreateIntToPtr(
697 IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
698 StackPtrTy);
699
700 // Save the stack pointer.
701 IRB.CreateStore(NewTop, UnsafeStackPtr);
702 if (DynamicTop)
703 IRB.CreateStore(NewTop, DynamicTop);
704
Evgeniy Stepanov9842d612015-11-25 22:52:30 +0000705 Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000706 if (AI->hasName() && isa<Instruction>(NewAI))
707 NewAI->takeName(AI);
708
709 replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true);
710 AI->replaceAllUsesWith(NewAI);
711 AI->eraseFromParent();
712 }
713
714 if (!DynamicAllocas.empty()) {
715 // Now go through the instructions again, replacing stacksave/stackrestore.
716 for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
717 Instruction *I = &*(It++);
718 auto II = dyn_cast<IntrinsicInst>(I);
719 if (!II)
720 continue;
721
722 if (II->getIntrinsicID() == Intrinsic::stacksave) {
723 IRBuilder<> IRB(II);
724 Instruction *LI = IRB.CreateLoad(UnsafeStackPtr);
725 LI->takeName(II);
726 II->replaceAllUsesWith(LI);
727 II->eraseFromParent();
728 } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
729 IRBuilder<> IRB(II);
730 Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
731 SI->takeName(II);
732 assert(II->use_empty());
733 II->eraseFromParent();
734 }
735 }
736 }
737}
738
739bool SafeStack::runOnFunction(Function &F) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000740 DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
741
742 if (!F.hasFnAttribute(Attribute::SafeStack)) {
743 DEBUG(dbgs() << "[SafeStack] safestack is not requested"
744 " for this function\n");
745 return false;
746 }
747
748 if (F.isDeclaration()) {
749 DEBUG(dbgs() << "[SafeStack] function definition"
750 " is not available\n");
751 return false;
752 }
753
David L Kreitzer7c7ee892016-10-04 20:57:19 +0000754 TL = TM ? TM->getSubtargetImpl(F)->getTargetLowering() : nullptr;
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000755 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000756
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000757 ++NumFunctions;
758
759 SmallVector<AllocaInst *, 16> StaticAllocas;
760 SmallVector<AllocaInst *, 4> DynamicAllocas;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000761 SmallVector<Argument *, 4> ByValArguments;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000762 SmallVector<ReturnInst *, 4> Returns;
763
764 // Collect all points where stack gets unwound and needs to be restored
765 // This is only necessary because the runtime (setjmp and unwind code) is
766 // not aware of the unsafe stack and won't unwind/restore it prorerly.
767 // To work around this problem without changing the runtime, we insert
768 // instrumentation to restore the unsafe stack pointer when necessary.
769 SmallVector<Instruction *, 4> StackRestorePoints;
770
771 // Find all static and dynamic alloca instructions that must be moved to the
772 // unsafe stack, all return instructions and stack restore points.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000773 findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
774 StackRestorePoints);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000775
776 if (StaticAllocas.empty() && DynamicAllocas.empty() &&
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000777 ByValArguments.empty() && StackRestorePoints.empty())
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000778 return false; // Nothing to do in this function.
779
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000780 if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
781 !ByValArguments.empty())
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000782 ++NumUnsafeStackFunctions; // This function has the unsafe stack.
783
784 if (!StackRestorePoints.empty())
785 ++NumUnsafeStackRestorePointsFunctions;
786
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000787 IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000788 UnsafeStackPtr = getOrCreateUnsafeStackPtr(IRB, F);
Peter Collingbournede26a912015-06-22 20:26:54 +0000789
Anna Zakscad79942016-02-02 01:03:11 +0000790 // Load the current stack pointer (we'll also use it as a base pointer).
791 // FIXME: use a dedicated register for it ?
792 Instruction *BasePointer =
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000793 IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
Anna Zakscad79942016-02-02 01:03:11 +0000794 assert(BasePointer->getType() == StackPtrTy);
795
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000796 AllocaInst *StackGuardSlot = nullptr;
797 // FIXME: implement weaker forms of stack protector.
798 if (F.hasFnAttribute(Attribute::StackProtect) ||
799 F.hasFnAttribute(Attribute::StackProtectStrong) ||
800 F.hasFnAttribute(Attribute::StackProtectReq)) {
801 Value *StackGuard = getStackGuard(IRB, F);
802 StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr);
803 IRB.CreateStore(StackGuard, StackGuardSlot);
804
805 for (ReturnInst *RI : Returns) {
806 IRBuilder<> IRBRet(RI);
807 checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
808 }
809 }
810
811 // The top of the unsafe stack after all unsafe static allocas are
812 // allocated.
813 Value *StaticTop =
814 moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, ByValArguments,
815 Returns, BasePointer, StackGuardSlot);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000816
817 // Safe stack object that stores the current unsafe stack top. It is updated
818 // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
819 // This is only needed if we need to restore stack pointer after longjmp
820 // or exceptions, and we have dynamic allocations.
821 // FIXME: a better alternative might be to store the unsafe stack pointer
822 // before setjmp / invoke instructions.
823 AllocaInst *DynamicTop = createStackRestorePoints(
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000824 IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000825
826 // Handle dynamic allocas.
827 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
828 DynamicAllocas);
829
Anna Zakscad79942016-02-02 01:03:11 +0000830 // Restore the unsafe stack pointer before each return.
831 for (ReturnInst *RI : Returns) {
832 IRB.SetInsertPoint(RI);
833 IRB.CreateStore(BasePointer, UnsafeStackPtr);
834 }
835
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000836 DEBUG(dbgs() << "[SafeStack] safestack applied\n");
837 return true;
838}
839
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000840} // anonymous namespace
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000841
842char SafeStack::ID = 0;
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000843INITIALIZE_TM_PASS_BEGIN(SafeStack, "safe-stack",
844 "Safe Stack instrumentation pass", false, false)
845INITIALIZE_TM_PASS_END(SafeStack, "safe-stack",
846 "Safe Stack instrumentation pass", false, false)
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000847
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000848FunctionPass *llvm::createSafeStackPass(const llvm::TargetMachine *TM) {
849 return new SafeStack(TM);
850}