blob: 51233be521be03e05935845ec9cee81e8a8c5ce2 [file] [log] [blame]
Eugene Zelenko618c5552017-09-13 21:15:20 +00001//===- SafeStack.cpp - Safe Stack Insertion -------------------------------===//
Peter Collingbourne82437bf2015-06-15 21:07:11 +00002//
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"
Eugene Zelenko618c5552017-09-13 21:15:20 +000020#include "llvm/ADT/APInt.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/SmallVector.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000024#include "llvm/ADT/Statistic.h"
Ahmed Bougacha00d68222017-05-10 00:39:22 +000025#include "llvm/Analysis/AssumptionCache.h"
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +000026#include "llvm/Analysis/BranchProbabilityInfo.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000027#include "llvm/Analysis/LoopInfo.h"
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000028#include "llvm/Analysis/ScalarEvolution.h"
29#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000030#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000031#include "llvm/CodeGen/TargetLowering.h"
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +000032#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000033#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000034#include "llvm/IR/Argument.h"
35#include "llvm/IR/Attributes.h"
36#include "llvm/IR/CallSite.h"
37#include "llvm/IR/ConstantRange.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000038#include "llvm/IR/Constants.h"
Benjamin Kramer390c33c2016-01-27 16:53:42 +000039#include "llvm/IR/DIBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000040#include "llvm/IR/DataLayout.h"
41#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000042#include "llvm/IR/Dominators.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000043#include "llvm/IR/Function.h"
Benjamin Kramer390c33c2016-01-27 16:53:42 +000044#include "llvm/IR/IRBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000045#include "llvm/IR/InstIterator.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000046#include "llvm/IR/Instruction.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000047#include "llvm/IR/Instructions.h"
48#include "llvm/IR/IntrinsicInst.h"
49#include "llvm/IR/Intrinsics.h"
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +000050#include "llvm/IR/MDBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000051#include "llvm/IR/Module.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000052#include "llvm/IR/Type.h"
53#include "llvm/IR/Use.h"
54#include "llvm/IR/User.h"
55#include "llvm/IR/Value.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000056#include "llvm/Pass.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000057#include "llvm/Support/Casting.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000058#include "llvm/Support/Debug.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000059#include "llvm/Support/ErrorHandling.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000060#include "llvm/Support/MathExtras.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000061#include "llvm/Support/raw_ostream.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000062#include "llvm/Target/TargetMachine.h"
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +000063#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000064#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000065#include <algorithm>
66#include <cassert>
67#include <cstdint>
68#include <string>
69#include <utility>
Peter Collingbourne82437bf2015-06-15 21:07:11 +000070
71using namespace llvm;
Evgeniy Stepanova5da2562016-06-29 20:37:43 +000072using namespace llvm::safestack;
Peter Collingbourne82437bf2015-06-15 21:07:11 +000073
Matthias Braun1527baa2017-05-25 21:26:32 +000074#define DEBUG_TYPE "safe-stack"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000075
76namespace llvm {
77
78STATISTIC(NumFunctions, "Total number of functions");
79STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
80STATISTIC(NumUnsafeStackRestorePointsFunctions,
81 "Number of functions that use setjmp or exceptions");
82
83STATISTIC(NumAllocas, "Total number of allocas");
84STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
85STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000086STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
Peter Collingbourne82437bf2015-06-15 21:07:11 +000087STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
88
89} // namespace llvm
90
91namespace {
92
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +000093/// Rewrite an SCEV expression for a memory access address to an expression that
94/// represents offset from the given alloca.
95///
96/// The implementation simply replaces all mentions of the alloca with zero.
97class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000098 const Value *AllocaPtr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +000099
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000100public:
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000101 AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
102 : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000103
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000104 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000105 if (Expr->getValue() == AllocaPtr)
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000106 return SE.getZero(Expr->getType());
107 return Expr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000108 }
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000109};
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000110
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000111/// The SafeStack pass splits the stack of each function into the safe
112/// stack, which is only accessed through memory safe dereferences (as
113/// determined statically), and the unsafe stack, which contains all
114/// local variables that are accessed in ways that we can't prove to
115/// be safe.
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000116class SafeStack {
117 Function &F;
118 const TargetLoweringBase &TL;
119 const DataLayout &DL;
120 ScalarEvolution &SE;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000121
122 Type *StackPtrTy;
123 Type *IntPtrTy;
124 Type *Int32Ty;
125 Type *Int8Ty;
126
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000127 Value *UnsafeStackPtr = nullptr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000128
129 /// Unsafe stack alignment. Each stack frame must ensure that the stack is
130 /// aligned to this value. We need to re-align the unsafe stack if the
131 /// alignment of any object on the stack exceeds this value.
132 ///
133 /// 16 seems like a reasonable upper bound on the alignment of objects that we
134 /// might expect to appear on the stack on most common targets.
135 enum { StackAlignment = 16 };
136
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000137 /// \brief Return the value of the stack canary.
138 Value *getStackGuard(IRBuilder<> &IRB, Function &F);
139
140 /// \brief Load stack guard from the frame and check if it has changed.
141 void checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
142 AllocaInst *StackGuardSlot, Value *StackGuard);
143
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000144 /// \brief Find all static allocas, dynamic allocas, return instructions and
145 /// stack restore points (exception unwind blocks and setjmp calls) in the
146 /// given function and append them to the respective vectors.
147 void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
148 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000149 SmallVectorImpl<Argument *> &ByValArguments,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000150 SmallVectorImpl<ReturnInst *> &Returns,
151 SmallVectorImpl<Instruction *> &StackRestorePoints);
152
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000153 /// \brief Calculate the allocation size of a given alloca. Returns 0 if the
154 /// size can not be statically determined.
155 uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
156
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000157 /// \brief Allocate space for all static allocas in \p StaticAllocas,
158 /// replace allocas with pointers into the unsafe stack and generate code to
159 /// restore the stack pointer before all return instructions in \p Returns.
160 ///
161 /// \returns A pointer to the top of the unsafe stack after all unsafe static
162 /// allocas are allocated.
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000163 Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000164 ArrayRef<AllocaInst *> StaticAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000165 ArrayRef<Argument *> ByValArguments,
Anna Zakscad79942016-02-02 01:03:11 +0000166 ArrayRef<ReturnInst *> Returns,
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000167 Instruction *BasePointer,
168 AllocaInst *StackGuardSlot);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000169
170 /// \brief Generate code to restore the stack after all stack restore points
171 /// in \p StackRestorePoints.
172 ///
173 /// \returns A local variable in which to maintain the dynamic top of the
174 /// unsafe stack if needed.
175 AllocaInst *
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000176 createStackRestorePoints(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000177 ArrayRef<Instruction *> StackRestorePoints,
178 Value *StaticTop, bool NeedDynamicTop);
179
180 /// \brief Replace all allocas in \p DynamicAllocas with code to allocate
181 /// space dynamically on the unsafe stack and store the dynamic unsafe stack
182 /// top to \p DynamicTop if non-null.
183 void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
184 AllocaInst *DynamicTop,
185 ArrayRef<AllocaInst *> DynamicAllocas);
186
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000187 bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000188
189 bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000190 const Value *AllocaPtr, uint64_t AllocaSize);
191 bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
192 uint64_t AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000193
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000194public:
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000195 SafeStack(Function &F, const TargetLoweringBase &TL, const DataLayout &DL,
196 ScalarEvolution &SE)
197 : F(F), TL(TL), DL(DL), SE(SE),
198 StackPtrTy(Type::getInt8PtrTy(F.getContext())),
199 IntPtrTy(DL.getIntPtrType(F.getContext())),
200 Int32Ty(Type::getInt32Ty(F.getContext())),
201 Int8Ty(Type::getInt8Ty(F.getContext())) {}
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000202
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000203 // Run the transformation on the associated function.
204 // Returns whether the function was changed.
205 bool run();
206};
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000207
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000208uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) {
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000209 uint64_t Size = DL.getTypeAllocSize(AI->getAllocatedType());
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000210 if (AI->isArrayAllocation()) {
211 auto C = dyn_cast<ConstantInt>(AI->getArraySize());
212 if (!C)
213 return 0;
214 Size *= C->getZExtValue();
215 }
216 return Size;
217}
218
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000219bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize,
220 const Value *AllocaPtr, uint64_t AllocaSize) {
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000221 AllocaOffsetRewriter Rewriter(SE, AllocaPtr);
222 const SCEV *Expr = Rewriter.visit(SE.getSCEV(Addr));
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000223
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000224 uint64_t BitWidth = SE.getTypeSizeInBits(Expr->getType());
225 ConstantRange AccessStartRange = SE.getUnsignedRange(Expr);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000226 ConstantRange SizeRange =
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000227 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize));
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000228 ConstantRange AccessRange = AccessStartRange.add(SizeRange);
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000229 ConstantRange AllocaRange =
230 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize));
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000231 bool Safe = AllocaRange.contains(AccessRange);
232
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000233 DEBUG(dbgs() << "[SafeStack] "
234 << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
235 << *AllocaPtr << "\n"
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000236 << " Access " << *Addr << "\n"
237 << " SCEV " << *Expr
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000238 << " U: " << SE.getUnsignedRange(Expr)
239 << ", S: " << SE.getSignedRange(Expr) << "\n"
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000240 << " Range " << AccessRange << "\n"
241 << " AllocaRange " << AllocaRange << "\n"
242 << " " << (Safe ? "safe" : "unsafe") << "\n");
243
244 return Safe;
245}
246
247bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000248 const Value *AllocaPtr,
249 uint64_t AllocaSize) {
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000250 // All MemIntrinsics have destination address in Arg0 and size in Arg2.
251 if (MI->getRawDest() != U) return true;
252 const auto *Len = dyn_cast<ConstantInt>(MI->getLength());
253 // Non-constant size => unsafe. FIXME: try SCEV getRange.
254 if (!Len) return false;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000255 return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000256}
257
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000258/// Check whether a given allocation must be put on the safe
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000259/// stack or not. The function analyzes all uses of AI and checks whether it is
260/// only accessed in a memory safe way (as decided statically).
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000261bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) {
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000262 // Go through all uses of this alloca and check whether all accesses to the
263 // allocated object are statically known to be memory safe and, hence, the
264 // object can be placed on the safe stack.
265 SmallPtrSet<const Value *, 16> Visited;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000266 SmallVector<const Value *, 8> WorkList;
267 WorkList.push_back(AllocaPtr);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000268
269 // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
270 while (!WorkList.empty()) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000271 const Value *V = WorkList.pop_back_val();
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000272 for (const Use &UI : V->uses()) {
273 auto I = cast<const Instruction>(UI.getUser());
274 assert(V == UI.get());
275
276 switch (I->getOpcode()) {
Eugene Zelenko618c5552017-09-13 21:15:20 +0000277 case Instruction::Load:
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000278 if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getType()), AllocaPtr,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000279 AllocaSize))
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000280 return false;
281 break;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000282
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000283 case Instruction::VAArg:
284 // "va-arg" from a pointer is safe.
285 break;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000286 case Instruction::Store:
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000287 if (V == I->getOperand(0)) {
288 // Stored the pointer - conservatively assume it may be unsafe.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000289 DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000290 << "\n store of address: " << *I << "\n");
291 return false;
292 }
293
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000294 if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getOperand(0)->getType()),
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000295 AllocaPtr, AllocaSize))
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000296 return false;
297 break;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000298
299 case Instruction::Ret:
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000300 // Information leak.
301 return false;
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000302
303 case Instruction::Call:
304 case Instruction::Invoke: {
305 ImmutableCallSite CS(I);
306
307 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
308 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
309 II->getIntrinsicID() == Intrinsic::lifetime_end)
310 continue;
311 }
312
313 if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000314 if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
315 DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000316 << "\n unsafe memintrinsic: " << *I
317 << "\n");
318 return false;
319 }
320 continue;
321 }
322
323 // LLVM 'nocapture' attribute is only set for arguments whose address
324 // is not stored, passed around, or used in any other non-trivial way.
325 // We assume that passing a pointer to an object as a 'nocapture
326 // readnone' argument is safe.
327 // FIXME: a more precise solution would require an interprocedural
328 // analysis here, which would look at all uses of an argument inside
329 // the function being called.
330 ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
331 for (ImmutableCallSite::arg_iterator A = B; A != E; ++A)
332 if (A->get() == V)
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000333 if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) ||
334 CS.doesNotAccessMemory()))) {
335 DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000336 << "\n unsafe call: " << *I << "\n");
337 return false;
338 }
339 continue;
340 }
341
342 default:
343 if (Visited.insert(I).second)
344 WorkList.push_back(cast<const Instruction>(I));
345 }
346 }
347 }
348
349 // All uses of the alloca are safe, we can place it on the safe stack.
350 return true;
351}
352
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000353Value *SafeStack::getStackGuard(IRBuilder<> &IRB, Function &F) {
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000354 Value *StackGuardVar = TL.getIRStackGuard(IRB);
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000355 if (!StackGuardVar)
356 StackGuardVar =
357 F.getParent()->getOrInsertGlobal("__stack_chk_guard", StackPtrTy);
358 return IRB.CreateLoad(StackGuardVar, "StackGuard");
359}
360
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000361void SafeStack::findInsts(Function &F,
362 SmallVectorImpl<AllocaInst *> &StaticAllocas,
363 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000364 SmallVectorImpl<Argument *> &ByValArguments,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000365 SmallVectorImpl<ReturnInst *> &Returns,
366 SmallVectorImpl<Instruction *> &StackRestorePoints) {
Nico Rieck78199512015-08-06 19:10:45 +0000367 for (Instruction &I : instructions(&F)) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000368 if (auto AI = dyn_cast<AllocaInst>(&I)) {
369 ++NumAllocas;
370
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000371 uint64_t Size = getStaticAllocaAllocationSize(AI);
372 if (IsSafeStackAlloca(AI, Size))
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000373 continue;
374
375 if (AI->isStaticAlloca()) {
376 ++NumUnsafeStaticAllocas;
377 StaticAllocas.push_back(AI);
378 } else {
379 ++NumUnsafeDynamicAllocas;
380 DynamicAllocas.push_back(AI);
381 }
382 } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
383 Returns.push_back(RI);
384 } else if (auto CI = dyn_cast<CallInst>(&I)) {
385 // setjmps require stack restore.
386 if (CI->getCalledFunction() && CI->canReturnTwice())
387 StackRestorePoints.push_back(CI);
388 } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
389 // Exception landing pads require stack restore.
390 StackRestorePoints.push_back(LP);
391 } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
392 if (II->getIntrinsicID() == Intrinsic::gcroot)
Eugene Zelenko618c5552017-09-13 21:15:20 +0000393 report_fatal_error(
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000394 "gcroot intrinsic not compatible with safestack attribute");
395 }
396 }
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000397 for (Argument &Arg : F.args()) {
398 if (!Arg.hasByValAttr())
399 continue;
400 uint64_t Size =
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000401 DL.getTypeStoreSize(Arg.getType()->getPointerElementType());
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000402 if (IsSafeStackAlloca(&Arg, Size))
403 continue;
404
405 ++NumUnsafeByValArguments;
406 ByValArguments.push_back(&Arg);
407 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000408}
409
410AllocaInst *
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000411SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000412 ArrayRef<Instruction *> StackRestorePoints,
413 Value *StaticTop, bool NeedDynamicTop) {
Anna Zakscad79942016-02-02 01:03:11 +0000414 assert(StaticTop && "The stack top isn't set.");
415
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000416 if (StackRestorePoints.empty())
417 return nullptr;
418
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000419 // We need the current value of the shadow stack pointer to restore
420 // after longjmp or exception catching.
421
422 // FIXME: On some platforms this could be handled by the longjmp/exception
423 // runtime itself.
424
425 AllocaInst *DynamicTop = nullptr;
Anna Zakscad79942016-02-02 01:03:11 +0000426 if (NeedDynamicTop) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000427 // If we also have dynamic alloca's, the stack pointer value changes
428 // throughout the function. For now we store it in an alloca.
429 DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
430 "unsafe_stack_dynamic_ptr");
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000431 IRB.CreateStore(StaticTop, DynamicTop);
Anna Zakscad79942016-02-02 01:03:11 +0000432 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000433
434 // Restore current stack pointer after longjmp/exception catch.
435 for (Instruction *I : StackRestorePoints) {
436 ++NumUnsafeStackRestorePoints;
437
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000438 IRB.SetInsertPoint(I->getNextNode());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000439 Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
440 IRB.CreateStore(CurrentTop, UnsafeStackPtr);
441 }
442
443 return DynamicTop;
444}
445
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000446void SafeStack::checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
447 AllocaInst *StackGuardSlot, Value *StackGuard) {
448 Value *V = IRB.CreateLoad(StackGuardSlot);
449 Value *Cmp = IRB.CreateICmpNE(StackGuard, V);
450
451 auto SuccessProb = BranchProbabilityInfo::getBranchProbStackProtector(true);
452 auto FailureProb = BranchProbabilityInfo::getBranchProbStackProtector(false);
453 MDNode *Weights = MDBuilder(F.getContext())
454 .createBranchWeights(SuccessProb.getNumerator(),
455 FailureProb.getNumerator());
456 Instruction *CheckTerm =
457 SplitBlockAndInsertIfThen(Cmp, &RI,
458 /* Unreachable */ true, Weights);
459 IRBuilder<> IRBFail(CheckTerm);
460 // FIXME: respect -fsanitize-trap / -ftrap-function here?
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000461 Constant *StackChkFail = F.getParent()->getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000462 "__stack_chk_fail", IRB.getVoidTy());
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000463 IRBFail.CreateCall(StackChkFail, {});
464}
465
Anna Zakscad79942016-02-02 01:03:11 +0000466/// We explicitly compute and set the unsafe stack layout for all unsafe
467/// static alloca instructions. We save the unsafe "base pointer" in the
468/// prologue into a local variable and restore it in the epilogue.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000469Value *SafeStack::moveStaticAllocasToUnsafeStack(
470 IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
Anna Zakscad79942016-02-02 01:03:11 +0000471 ArrayRef<Argument *> ByValArguments, ArrayRef<ReturnInst *> Returns,
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000472 Instruction *BasePointer, AllocaInst *StackGuardSlot) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000473 if (StaticAllocas.empty() && ByValArguments.empty())
Anna Zakscad79942016-02-02 01:03:11 +0000474 return BasePointer;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000475
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000476 DIBuilder DIB(*F.getParent());
477
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000478 StackColoring SSC(F, StaticAllocas);
479 SSC.run();
480 SSC.removeAllMarkers();
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000481
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000482 // Unsafe stack always grows down.
483 StackLayout SSL(StackAlignment);
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000484 if (StackGuardSlot) {
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000485 Type *Ty = StackGuardSlot->getAllocatedType();
486 unsigned Align =
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000487 std::max(DL.getPrefTypeAlignment(Ty), StackGuardSlot->getAlignment());
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000488 SSL.addObject(StackGuardSlot, getStaticAllocaAllocationSize(StackGuardSlot),
Evgeniy Stepanov906f6fb2016-07-26 00:05:14 +0000489 Align, SSC.getFullLiveRange());
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000490 }
491
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000492 for (Argument *Arg : ByValArguments) {
493 Type *Ty = Arg->getType()->getPointerElementType();
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000494 uint64_t Size = DL.getTypeStoreSize(Ty);
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000495 if (Size == 0)
496 Size = 1; // Don't create zero-sized stack objects.
497
498 // Ensure the object is properly aligned.
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000499 unsigned Align = std::max((unsigned)DL.getPrefTypeAlignment(Ty),
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000500 Arg->getParamAlignment());
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000501 SSL.addObject(Arg, Size, Align, SSC.getFullLiveRange());
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000502 }
503
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000504 for (AllocaInst *AI : StaticAllocas) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000505 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000506 uint64_t Size = getStaticAllocaAllocationSize(AI);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000507 if (Size == 0)
508 Size = 1; // Don't create zero-sized stack objects.
509
510 // Ensure the object is properly aligned.
511 unsigned Align =
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000512 std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000513
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000514 SSL.addObject(AI, Size, Align, SSC.getLiveRange(AI));
515 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000516
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000517 SSL.computeLayout();
518 unsigned FrameAlignment = SSL.getFrameAlignment();
519
520 // FIXME: tell SSL that we start at a less-then-MaxAlignment aligned location
521 // (AlignmentSkew).
522 if (FrameAlignment > StackAlignment) {
523 // Re-align the base pointer according to the max requested alignment.
524 assert(isPowerOf2_32(FrameAlignment));
525 IRB.SetInsertPoint(BasePointer->getNextNode());
526 BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
527 IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
528 ConstantInt::get(IntPtrTy, ~uint64_t(FrameAlignment - 1))),
529 StackPtrTy));
530 }
531
532 IRB.SetInsertPoint(BasePointer->getNextNode());
533
534 if (StackGuardSlot) {
535 unsigned Offset = SSL.getObjectOffset(StackGuardSlot);
536 Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
537 ConstantInt::get(Int32Ty, -Offset));
538 Value *NewAI =
539 IRB.CreateBitCast(Off, StackGuardSlot->getType(), "StackGuardSlot");
540
541 // Replace alloc with the new location.
542 StackGuardSlot->replaceAllUsesWith(NewAI);
543 StackGuardSlot->eraseFromParent();
544 }
545
546 for (Argument *Arg : ByValArguments) {
547 unsigned Offset = SSL.getObjectOffset(Arg);
548 Type *Ty = Arg->getType()->getPointerElementType();
549
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000550 uint64_t Size = DL.getTypeStoreSize(Ty);
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000551 if (Size == 0)
552 Size = 1; // Don't create zero-sized stack objects.
553
554 Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
555 ConstantInt::get(Int32Ty, -Offset));
556 Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
557 Arg->getName() + ".unsafe-byval");
558
559 // Replace alloc with the new location.
560 replaceDbgDeclare(Arg, BasePointer, BasePointer->getNextNode(), DIB,
Adrian Prantld1317012017-12-08 21:58:18 +0000561 DIExpression::NoDeref, -Offset, DIExpression::NoDeref);
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000562 Arg->replaceAllUsesWith(NewArg);
563 IRB.SetInsertPoint(cast<Instruction>(NewArg)->getNextNode());
564 IRB.CreateMemCpy(Off, Arg, Size, Arg->getParamAlignment());
565 }
566
567 // Allocate space for every unsafe static AllocaInst on the unsafe stack.
568 for (AllocaInst *AI : StaticAllocas) {
569 IRB.SetInsertPoint(AI);
570 unsigned Offset = SSL.getObjectOffset(AI);
571
572 uint64_t Size = getStaticAllocaAllocationSize(AI);
573 if (Size == 0)
574 Size = 1; // Don't create zero-sized stack objects.
575
Adrian Prantld1317012017-12-08 21:58:18 +0000576 replaceDbgDeclareForAlloca(AI, BasePointer, DIB, DIExpression::NoDeref,
577 -Offset, DIExpression::NoDeref);
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000578 replaceDbgValueForAlloca(AI, BasePointer, DIB, -Offset);
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000579
580 // Replace uses of the alloca with the new location.
581 // Insert address calculation close to each use to work around PR27844.
582 std::string Name = std::string(AI->getName()) + ".unsafe";
583 while (!AI->use_empty()) {
584 Use &U = *AI->use_begin();
585 Instruction *User = cast<Instruction>(U.getUser());
586
587 Instruction *InsertBefore;
588 if (auto *PHI = dyn_cast<PHINode>(User))
589 InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
590 else
591 InsertBefore = User;
592
593 IRBuilder<> IRBUser(InsertBefore);
594 Value *Off = IRBUser.CreateGEP(BasePointer, // BasePointer is i8*
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000595 ConstantInt::get(Int32Ty, -Offset));
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000596 Value *Replacement = IRBUser.CreateBitCast(Off, AI->getType(), Name);
597
598 if (auto *PHI = dyn_cast<PHINode>(User)) {
599 // PHI nodes may have multiple incoming edges from the same BB (why??),
600 // all must be updated at once with the same incoming value.
601 auto *BB = PHI->getIncomingBlock(U);
602 for (unsigned I = 0; I < PHI->getNumIncomingValues(); ++I)
603 if (PHI->getIncomingBlock(I) == BB)
604 PHI->setIncomingValue(I, Replacement);
605 } else {
606 U.set(Replacement);
607 }
608 }
609
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000610 AI->eraseFromParent();
611 }
612
613 // Re-align BasePointer so that our callees would see it aligned as
614 // expected.
615 // FIXME: no need to update BasePointer in leaf functions.
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000616 unsigned FrameSize = alignTo(SSL.getFrameSize(), StackAlignment);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000617
618 // Update shadow stack pointer in the function epilogue.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000619 IRB.SetInsertPoint(BasePointer->getNextNode());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000620
621 Value *StaticTop =
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000622 IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -FrameSize),
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000623 "unsafe_stack_static_top");
624 IRB.CreateStore(StaticTop, UnsafeStackPtr);
625 return StaticTop;
626}
627
628void SafeStack::moveDynamicAllocasToUnsafeStack(
629 Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
630 ArrayRef<AllocaInst *> DynamicAllocas) {
631 DIBuilder DIB(*F.getParent());
632
633 for (AllocaInst *AI : DynamicAllocas) {
634 IRBuilder<> IRB(AI);
635
636 // Compute the new SP value (after AI).
637 Value *ArraySize = AI->getArraySize();
638 if (ArraySize->getType() != IntPtrTy)
639 ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
640
641 Type *Ty = AI->getAllocatedType();
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000642 uint64_t TySize = DL.getTypeAllocSize(Ty);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000643 Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
644
645 Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy);
646 SP = IRB.CreateSub(SP, Size);
647
648 // Align the SP value to satisfy the AllocaInst, type and stack alignments.
649 unsigned Align = std::max(
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000650 std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment()),
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000651 (unsigned)StackAlignment);
652
653 assert(isPowerOf2_32(Align));
654 Value *NewTop = IRB.CreateIntToPtr(
655 IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
656 StackPtrTy);
657
658 // Save the stack pointer.
659 IRB.CreateStore(NewTop, UnsafeStackPtr);
660 if (DynamicTop)
661 IRB.CreateStore(NewTop, DynamicTop);
662
Evgeniy Stepanov9842d612015-11-25 22:52:30 +0000663 Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000664 if (AI->hasName() && isa<Instruction>(NewAI))
665 NewAI->takeName(AI);
666
Adrian Prantld1317012017-12-08 21:58:18 +0000667 replaceDbgDeclareForAlloca(AI, NewAI, DIB, DIExpression::NoDeref, 0,
668 DIExpression::NoDeref);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000669 AI->replaceAllUsesWith(NewAI);
670 AI->eraseFromParent();
671 }
672
673 if (!DynamicAllocas.empty()) {
674 // Now go through the instructions again, replacing stacksave/stackrestore.
675 for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
676 Instruction *I = &*(It++);
677 auto II = dyn_cast<IntrinsicInst>(I);
678 if (!II)
679 continue;
680
681 if (II->getIntrinsicID() == Intrinsic::stacksave) {
682 IRBuilder<> IRB(II);
683 Instruction *LI = IRB.CreateLoad(UnsafeStackPtr);
684 LI->takeName(II);
685 II->replaceAllUsesWith(LI);
686 II->eraseFromParent();
687 } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
688 IRBuilder<> IRB(II);
689 Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
690 SI->takeName(II);
691 assert(II->use_empty());
692 II->eraseFromParent();
693 }
694 }
695 }
696}
697
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000698bool SafeStack::run() {
699 assert(F.hasFnAttribute(Attribute::SafeStack) &&
700 "Can't run SafeStack on a function without the attribute");
701 assert(!F.isDeclaration() && "Can't run SafeStack on a function declaration");
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000702
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000703 ++NumFunctions;
704
705 SmallVector<AllocaInst *, 16> StaticAllocas;
706 SmallVector<AllocaInst *, 4> DynamicAllocas;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000707 SmallVector<Argument *, 4> ByValArguments;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000708 SmallVector<ReturnInst *, 4> Returns;
709
710 // Collect all points where stack gets unwound and needs to be restored
711 // This is only necessary because the runtime (setjmp and unwind code) is
Michael LeMay14153552016-10-17 19:09:19 +0000712 // not aware of the unsafe stack and won't unwind/restore it properly.
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000713 // To work around this problem without changing the runtime, we insert
714 // instrumentation to restore the unsafe stack pointer when necessary.
715 SmallVector<Instruction *, 4> StackRestorePoints;
716
717 // Find all static and dynamic alloca instructions that must be moved to the
718 // unsafe stack, all return instructions and stack restore points.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000719 findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
720 StackRestorePoints);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000721
722 if (StaticAllocas.empty() && DynamicAllocas.empty() &&
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000723 ByValArguments.empty() && StackRestorePoints.empty())
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000724 return false; // Nothing to do in this function.
725
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000726 if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
727 !ByValArguments.empty())
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000728 ++NumUnsafeStackFunctions; // This function has the unsafe stack.
729
730 if (!StackRestorePoints.empty())
731 ++NumUnsafeStackRestorePointsFunctions;
732
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000733 IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000734 UnsafeStackPtr = TL.getSafeStackPointerLocation(IRB);
Peter Collingbournede26a912015-06-22 20:26:54 +0000735
Anna Zakscad79942016-02-02 01:03:11 +0000736 // Load the current stack pointer (we'll also use it as a base pointer).
737 // FIXME: use a dedicated register for it ?
738 Instruction *BasePointer =
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000739 IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
Anna Zakscad79942016-02-02 01:03:11 +0000740 assert(BasePointer->getType() == StackPtrTy);
741
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000742 AllocaInst *StackGuardSlot = nullptr;
743 // FIXME: implement weaker forms of stack protector.
744 if (F.hasFnAttribute(Attribute::StackProtect) ||
745 F.hasFnAttribute(Attribute::StackProtectStrong) ||
746 F.hasFnAttribute(Attribute::StackProtectReq)) {
747 Value *StackGuard = getStackGuard(IRB, F);
748 StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr);
749 IRB.CreateStore(StackGuard, StackGuardSlot);
750
751 for (ReturnInst *RI : Returns) {
752 IRBuilder<> IRBRet(RI);
753 checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
754 }
755 }
756
757 // The top of the unsafe stack after all unsafe static allocas are
758 // allocated.
759 Value *StaticTop =
760 moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, ByValArguments,
761 Returns, BasePointer, StackGuardSlot);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000762
763 // Safe stack object that stores the current unsafe stack top. It is updated
764 // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
765 // This is only needed if we need to restore stack pointer after longjmp
766 // or exceptions, and we have dynamic allocations.
767 // FIXME: a better alternative might be to store the unsafe stack pointer
768 // before setjmp / invoke instructions.
769 AllocaInst *DynamicTop = createStackRestorePoints(
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000770 IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000771
772 // Handle dynamic allocas.
773 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
774 DynamicAllocas);
775
Anna Zakscad79942016-02-02 01:03:11 +0000776 // Restore the unsafe stack pointer before each return.
777 for (ReturnInst *RI : Returns) {
778 IRB.SetInsertPoint(RI);
779 IRB.CreateStore(BasePointer, UnsafeStackPtr);
780 }
781
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000782 DEBUG(dbgs() << "[SafeStack] safestack applied\n");
783 return true;
784}
785
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000786class SafeStackLegacyPass : public FunctionPass {
Eugene Zelenko618c5552017-09-13 21:15:20 +0000787 const TargetMachine *TM = nullptr;
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000788
789public:
790 static char ID; // Pass identification, replacement for typeid..
Eugene Zelenko618c5552017-09-13 21:15:20 +0000791
792 SafeStackLegacyPass() : FunctionPass(ID) {
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000793 initializeSafeStackLegacyPassPass(*PassRegistry::getPassRegistry());
794 }
795
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000796 void getAnalysisUsage(AnalysisUsage &AU) const override {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000797 AU.addRequired<TargetPassConfig>();
Ahmed Bougacha8c358e32017-05-10 00:39:25 +0000798 AU.addRequired<TargetLibraryInfoWrapperPass>();
799 AU.addRequired<AssumptionCacheTracker>();
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000800 }
801
802 bool runOnFunction(Function &F) override {
803 DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
804
805 if (!F.hasFnAttribute(Attribute::SafeStack)) {
806 DEBUG(dbgs() << "[SafeStack] safestack is not requested"
807 " for this function\n");
808 return false;
809 }
810
811 if (F.isDeclaration()) {
812 DEBUG(dbgs() << "[SafeStack] function definition"
813 " is not available\n");
814 return false;
815 }
816
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000817 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000818 auto *TL = TM->getSubtargetImpl(F)->getTargetLowering();
819 if (!TL)
820 report_fatal_error("TargetLowering instance is required");
821
822 auto *DL = &F.getParent()->getDataLayout();
Ahmed Bougacha8c358e32017-05-10 00:39:25 +0000823 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
824 auto &ACT = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
825
826 // Compute DT and LI only for functions that have the attribute.
827 // This is only useful because the legacy pass manager doesn't let us
828 // compute analyzes lazily.
829 // In the backend pipeline, nothing preserves DT before SafeStack, so we
830 // would otherwise always compute it wastefully, even if there is no
831 // function with the safestack attribute.
832 DominatorTree DT(F);
833 LoopInfo LI(DT);
834
835 ScalarEvolution SE(F, TLI, ACT, DT, LI);
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000836
837 return SafeStack(F, *TL, *DL, SE).run();
838 }
839};
840
Eugene Zelenko618c5552017-09-13 21:15:20 +0000841} // end anonymous namespace
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000842
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000843char SafeStackLegacyPass::ID = 0;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000844
Matthias Braun1527baa2017-05-25 21:26:32 +0000845INITIALIZE_PASS_BEGIN(SafeStackLegacyPass, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000846 "Safe Stack instrumentation pass", false, false)
847INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
Matthias Braun1527baa2017-05-25 21:26:32 +0000848INITIALIZE_PASS_END(SafeStackLegacyPass, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000849 "Safe Stack instrumentation pass", false, false)
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000850
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000851FunctionPass *llvm::createSafeStackPass() { return new SafeStackLegacyPass(); }