blob: fc110c683f4d524292213c36315f33074c95761d [file] [log] [blame]
Eugene Zelenko618c5552017-09-13 21:15:20 +00001//===- SafeStack.cpp - Safe Stack Insertion -------------------------------===//
Peter Collingbourne82437bf2015-06-15 21:07:11 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Peter Collingbourne82437bf2015-06-15 21:07:11 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass splits the stack into the safe stack (kept as-is for LLVM backend)
10// and the unsafe stack (explicitly allocated and managed through the runtime
11// support library).
12//
13// http://clang.llvm.org/docs/SafeStack.html
14//
15//===----------------------------------------------------------------------===//
16
Evgeniy Stepanova5da2562016-06-29 20:37:43 +000017#include "SafeStackColoring.h"
18#include "SafeStackLayout.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000019#include "llvm/ADT/APInt.h"
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000023#include "llvm/ADT/Statistic.h"
Ahmed Bougacha00d68222017-05-10 00:39:22 +000024#include "llvm/Analysis/AssumptionCache.h"
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +000025#include "llvm/Analysis/BranchProbabilityInfo.h"
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +000026#include "llvm/Analysis/InlineCost.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 Blaikie31b98d22018-06-04 21:23:21 +000031#include "llvm/Transforms/Utils/Local.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000032#include "llvm/CodeGen/TargetLowering.h"
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +000033#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000034#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000035#include "llvm/IR/Argument.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/CallSite.h"
38#include "llvm/IR/ConstantRange.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000039#include "llvm/IR/Constants.h"
Benjamin Kramer390c33c2016-01-27 16:53:42 +000040#include "llvm/IR/DIBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000041#include "llvm/IR/DataLayout.h"
42#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000043#include "llvm/IR/Dominators.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000044#include "llvm/IR/Function.h"
Benjamin Kramer390c33c2016-01-27 16:53:42 +000045#include "llvm/IR/IRBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000046#include "llvm/IR/InstIterator.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000047#include "llvm/IR/Instruction.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000048#include "llvm/IR/Instructions.h"
49#include "llvm/IR/IntrinsicInst.h"
50#include "llvm/IR/Intrinsics.h"
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +000051#include "llvm/IR/MDBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000052#include "llvm/IR/Module.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000053#include "llvm/IR/Type.h"
54#include "llvm/IR/Use.h"
55#include "llvm/IR/User.h"
56#include "llvm/IR/Value.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000057#include "llvm/Pass.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000058#include "llvm/Support/Casting.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000059#include "llvm/Support/Debug.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000060#include "llvm/Support/ErrorHandling.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000061#include "llvm/Support/MathExtras.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000062#include "llvm/Support/raw_ostream.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000063#include "llvm/Target/TargetMachine.h"
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +000064#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +000065#include "llvm/Transforms/Utils/Cloning.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000066#include <algorithm>
67#include <cassert>
68#include <cstdint>
69#include <string>
70#include <utility>
Peter Collingbourne82437bf2015-06-15 21:07:11 +000071
72using namespace llvm;
Evgeniy Stepanova5da2562016-06-29 20:37:43 +000073using namespace llvm::safestack;
Peter Collingbourne82437bf2015-06-15 21:07:11 +000074
Matthias Braun1527baa2017-05-25 21:26:32 +000075#define DEBUG_TYPE "safe-stack"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000076
77namespace llvm {
78
79STATISTIC(NumFunctions, "Total number of functions");
80STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
81STATISTIC(NumUnsafeStackRestorePointsFunctions,
82 "Number of functions that use setjmp or exceptions");
83
84STATISTIC(NumAllocas, "Total number of allocas");
85STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
86STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000087STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
Peter Collingbourne82437bf2015-06-15 21:07:11 +000088STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
89
90} // namespace llvm
91
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +000092/// Use __safestack_pointer_address even if the platform has a faster way of
93/// access safe stack pointer.
94static cl::opt<bool>
95 SafeStackUsePointerAddress("safestack-use-pointer-address",
96 cl::init(false), cl::Hidden);
97
98
Peter Collingbourne82437bf2015-06-15 21:07:11 +000099namespace {
100
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000101/// Rewrite an SCEV expression for a memory access address to an expression that
102/// represents offset from the given alloca.
103///
104/// The implementation simply replaces all mentions of the alloca with zero.
105class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000106 const Value *AllocaPtr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000107
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000108public:
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000109 AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
110 : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000111
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000112 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000113 if (Expr->getValue() == AllocaPtr)
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000114 return SE.getZero(Expr->getType());
115 return Expr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000116 }
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000117};
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000118
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000119/// The SafeStack pass splits the stack of each function into the safe
120/// stack, which is only accessed through memory safe dereferences (as
121/// determined statically), and the unsafe stack, which contains all
122/// local variables that are accessed in ways that we can't prove to
123/// be safe.
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000124class SafeStack {
125 Function &F;
126 const TargetLoweringBase &TL;
127 const DataLayout &DL;
128 ScalarEvolution &SE;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000129
130 Type *StackPtrTy;
131 Type *IntPtrTy;
132 Type *Int32Ty;
133 Type *Int8Ty;
134
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000135 Value *UnsafeStackPtr = nullptr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000136
137 /// Unsafe stack alignment. Each stack frame must ensure that the stack is
138 /// aligned to this value. We need to re-align the unsafe stack if the
139 /// alignment of any object on the stack exceeds this value.
140 ///
141 /// 16 seems like a reasonable upper bound on the alignment of objects that we
142 /// might expect to appear on the stack on most common targets.
143 enum { StackAlignment = 16 };
144
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000145 /// Return the value of the stack canary.
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000146 Value *getStackGuard(IRBuilder<> &IRB, Function &F);
147
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000148 /// Load stack guard from the frame and check if it has changed.
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000149 void checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
150 AllocaInst *StackGuardSlot, Value *StackGuard);
151
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000152 /// Find all static allocas, dynamic allocas, return instructions and
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000153 /// stack restore points (exception unwind blocks and setjmp calls) in the
154 /// given function and append them to the respective vectors.
155 void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
156 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000157 SmallVectorImpl<Argument *> &ByValArguments,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000158 SmallVectorImpl<ReturnInst *> &Returns,
159 SmallVectorImpl<Instruction *> &StackRestorePoints);
160
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000161 /// Calculate the allocation size of a given alloca. Returns 0 if the
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000162 /// size can not be statically determined.
163 uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
164
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000165 /// Allocate space for all static allocas in \p StaticAllocas,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000166 /// replace allocas with pointers into the unsafe stack and generate code to
167 /// restore the stack pointer before all return instructions in \p Returns.
168 ///
169 /// \returns A pointer to the top of the unsafe stack after all unsafe static
170 /// allocas are allocated.
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000171 Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000172 ArrayRef<AllocaInst *> StaticAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000173 ArrayRef<Argument *> ByValArguments,
Anna Zakscad79942016-02-02 01:03:11 +0000174 ArrayRef<ReturnInst *> Returns,
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000175 Instruction *BasePointer,
176 AllocaInst *StackGuardSlot);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000177
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000178 /// Generate code to restore the stack after all stack restore points
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000179 /// in \p StackRestorePoints.
180 ///
181 /// \returns A local variable in which to maintain the dynamic top of the
182 /// unsafe stack if needed.
183 AllocaInst *
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000184 createStackRestorePoints(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000185 ArrayRef<Instruction *> StackRestorePoints,
186 Value *StaticTop, bool NeedDynamicTop);
187
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000188 /// Replace all allocas in \p DynamicAllocas with code to allocate
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000189 /// space dynamically on the unsafe stack and store the dynamic unsafe stack
190 /// top to \p DynamicTop if non-null.
191 void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
192 AllocaInst *DynamicTop,
193 ArrayRef<AllocaInst *> DynamicAllocas);
194
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000195 bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000196
197 bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000198 const Value *AllocaPtr, uint64_t AllocaSize);
199 bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
200 uint64_t AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000201
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000202 bool ShouldInlinePointerAddress(CallSite &CS);
203 void TryInlinePointerAddress();
204
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000205public:
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000206 SafeStack(Function &F, const TargetLoweringBase &TL, const DataLayout &DL,
207 ScalarEvolution &SE)
208 : F(F), TL(TL), DL(DL), SE(SE),
209 StackPtrTy(Type::getInt8PtrTy(F.getContext())),
210 IntPtrTy(DL.getIntPtrType(F.getContext())),
211 Int32Ty(Type::getInt32Ty(F.getContext())),
212 Int8Ty(Type::getInt8Ty(F.getContext())) {}
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000213
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000214 // Run the transformation on the associated function.
215 // Returns whether the function was changed.
216 bool run();
217};
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000218
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000219uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) {
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000220 uint64_t Size = DL.getTypeAllocSize(AI->getAllocatedType());
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000221 if (AI->isArrayAllocation()) {
222 auto C = dyn_cast<ConstantInt>(AI->getArraySize());
223 if (!C)
224 return 0;
225 Size *= C->getZExtValue();
226 }
227 return Size;
228}
229
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000230bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize,
231 const Value *AllocaPtr, uint64_t AllocaSize) {
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000232 AllocaOffsetRewriter Rewriter(SE, AllocaPtr);
233 const SCEV *Expr = Rewriter.visit(SE.getSCEV(Addr));
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000234
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000235 uint64_t BitWidth = SE.getTypeSizeInBits(Expr->getType());
236 ConstantRange AccessStartRange = SE.getUnsignedRange(Expr);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000237 ConstantRange SizeRange =
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000238 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize));
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000239 ConstantRange AccessRange = AccessStartRange.add(SizeRange);
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000240 ConstantRange AllocaRange =
241 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize));
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000242 bool Safe = AllocaRange.contains(AccessRange);
243
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000244 LLVM_DEBUG(
245 dbgs() << "[SafeStack] "
246 << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
247 << *AllocaPtr << "\n"
248 << " Access " << *Addr << "\n"
249 << " SCEV " << *Expr
250 << " U: " << SE.getUnsignedRange(Expr)
251 << ", S: " << SE.getSignedRange(Expr) << "\n"
252 << " Range " << AccessRange << "\n"
253 << " AllocaRange " << AllocaRange << "\n"
254 << " " << (Safe ? "safe" : "unsafe") << "\n");
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000255
256 return Safe;
257}
258
259bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000260 const Value *AllocaPtr,
261 uint64_t AllocaSize) {
Vlad Tsyrklevich2499aee2018-08-30 20:44:51 +0000262 if (auto MTI = dyn_cast<MemTransferInst>(MI)) {
263 if (MTI->getRawSource() != U && MTI->getRawDest() != U)
264 return true;
265 } else {
266 if (MI->getRawDest() != U)
267 return true;
268 }
269
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000270 const auto *Len = dyn_cast<ConstantInt>(MI->getLength());
271 // Non-constant size => unsafe. FIXME: try SCEV getRange.
272 if (!Len) return false;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000273 return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000274}
275
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000276/// Check whether a given allocation must be put on the safe
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000277/// stack or not. The function analyzes all uses of AI and checks whether it is
278/// only accessed in a memory safe way (as decided statically).
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000279bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) {
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000280 // Go through all uses of this alloca and check whether all accesses to the
281 // allocated object are statically known to be memory safe and, hence, the
282 // object can be placed on the safe stack.
283 SmallPtrSet<const Value *, 16> Visited;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000284 SmallVector<const Value *, 8> WorkList;
285 WorkList.push_back(AllocaPtr);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000286
287 // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
288 while (!WorkList.empty()) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000289 const Value *V = WorkList.pop_back_val();
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000290 for (const Use &UI : V->uses()) {
291 auto I = cast<const Instruction>(UI.getUser());
292 assert(V == UI.get());
293
294 switch (I->getOpcode()) {
Eugene Zelenko618c5552017-09-13 21:15:20 +0000295 case Instruction::Load:
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000296 if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getType()), AllocaPtr,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000297 AllocaSize))
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000298 return false;
299 break;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000300
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000301 case Instruction::VAArg:
302 // "va-arg" from a pointer is safe.
303 break;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000304 case Instruction::Store:
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000305 if (V == I->getOperand(0)) {
306 // Stored the pointer - conservatively assume it may be unsafe.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000307 LLVM_DEBUG(dbgs()
308 << "[SafeStack] Unsafe alloca: " << *AllocaPtr
309 << "\n store of address: " << *I << "\n");
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000310 return false;
311 }
312
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000313 if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getOperand(0)->getType()),
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000314 AllocaPtr, AllocaSize))
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000315 return false;
316 break;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000317
318 case Instruction::Ret:
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000319 // Information leak.
320 return false;
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000321
322 case Instruction::Call:
323 case Instruction::Invoke: {
324 ImmutableCallSite CS(I);
325
Vedant Kumarb264d692018-12-21 21:49:40 +0000326 if (I->isLifetimeStartOrEnd())
327 continue;
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000328
329 if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000330 if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000331 LLVM_DEBUG(dbgs()
332 << "[SafeStack] Unsafe alloca: " << *AllocaPtr
333 << "\n unsafe memintrinsic: " << *I << "\n");
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000334 return false;
335 }
336 continue;
337 }
338
339 // LLVM 'nocapture' attribute is only set for arguments whose address
340 // is not stored, passed around, or used in any other non-trivial way.
341 // We assume that passing a pointer to an object as a 'nocapture
342 // readnone' argument is safe.
343 // FIXME: a more precise solution would require an interprocedural
344 // analysis here, which would look at all uses of an argument inside
345 // the function being called.
346 ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
347 for (ImmutableCallSite::arg_iterator A = B; A != E; ++A)
348 if (A->get() == V)
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000349 if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) ||
350 CS.doesNotAccessMemory()))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000351 LLVM_DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
352 << "\n unsafe call: " << *I << "\n");
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000353 return false;
354 }
355 continue;
356 }
357
358 default:
359 if (Visited.insert(I).second)
360 WorkList.push_back(cast<const Instruction>(I));
361 }
362 }
363 }
364
365 // All uses of the alloca are safe, we can place it on the safe stack.
366 return true;
367}
368
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000369Value *SafeStack::getStackGuard(IRBuilder<> &IRB, Function &F) {
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000370 Value *StackGuardVar = TL.getIRStackGuard(IRB);
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000371 if (!StackGuardVar)
372 StackGuardVar =
373 F.getParent()->getOrInsertGlobal("__stack_chk_guard", StackPtrTy);
James Y Knight14359ef2019-02-01 20:44:24 +0000374 return IRB.CreateLoad(StackPtrTy, StackGuardVar, "StackGuard");
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000375}
376
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000377void SafeStack::findInsts(Function &F,
378 SmallVectorImpl<AllocaInst *> &StaticAllocas,
379 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000380 SmallVectorImpl<Argument *> &ByValArguments,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000381 SmallVectorImpl<ReturnInst *> &Returns,
382 SmallVectorImpl<Instruction *> &StackRestorePoints) {
Nico Rieck78199512015-08-06 19:10:45 +0000383 for (Instruction &I : instructions(&F)) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000384 if (auto AI = dyn_cast<AllocaInst>(&I)) {
385 ++NumAllocas;
386
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000387 uint64_t Size = getStaticAllocaAllocationSize(AI);
388 if (IsSafeStackAlloca(AI, Size))
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000389 continue;
390
391 if (AI->isStaticAlloca()) {
392 ++NumUnsafeStaticAllocas;
393 StaticAllocas.push_back(AI);
394 } else {
395 ++NumUnsafeDynamicAllocas;
396 DynamicAllocas.push_back(AI);
397 }
398 } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
399 Returns.push_back(RI);
400 } else if (auto CI = dyn_cast<CallInst>(&I)) {
401 // setjmps require stack restore.
402 if (CI->getCalledFunction() && CI->canReturnTwice())
403 StackRestorePoints.push_back(CI);
404 } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
405 // Exception landing pads require stack restore.
406 StackRestorePoints.push_back(LP);
407 } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
408 if (II->getIntrinsicID() == Intrinsic::gcroot)
Eugene Zelenko618c5552017-09-13 21:15:20 +0000409 report_fatal_error(
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000410 "gcroot intrinsic not compatible with safestack attribute");
411 }
412 }
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000413 for (Argument &Arg : F.args()) {
414 if (!Arg.hasByValAttr())
415 continue;
416 uint64_t Size =
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000417 DL.getTypeStoreSize(Arg.getType()->getPointerElementType());
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000418 if (IsSafeStackAlloca(&Arg, Size))
419 continue;
420
421 ++NumUnsafeByValArguments;
422 ByValArguments.push_back(&Arg);
423 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000424}
425
426AllocaInst *
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000427SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000428 ArrayRef<Instruction *> StackRestorePoints,
429 Value *StaticTop, bool NeedDynamicTop) {
Anna Zakscad79942016-02-02 01:03:11 +0000430 assert(StaticTop && "The stack top isn't set.");
431
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000432 if (StackRestorePoints.empty())
433 return nullptr;
434
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000435 // We need the current value of the shadow stack pointer to restore
436 // after longjmp or exception catching.
437
438 // FIXME: On some platforms this could be handled by the longjmp/exception
439 // runtime itself.
440
441 AllocaInst *DynamicTop = nullptr;
Anna Zakscad79942016-02-02 01:03:11 +0000442 if (NeedDynamicTop) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000443 // If we also have dynamic alloca's, the stack pointer value changes
444 // throughout the function. For now we store it in an alloca.
445 DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
446 "unsafe_stack_dynamic_ptr");
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000447 IRB.CreateStore(StaticTop, DynamicTop);
Anna Zakscad79942016-02-02 01:03:11 +0000448 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000449
450 // Restore current stack pointer after longjmp/exception catch.
451 for (Instruction *I : StackRestorePoints) {
452 ++NumUnsafeStackRestorePoints;
453
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000454 IRB.SetInsertPoint(I->getNextNode());
James Y Knight14359ef2019-02-01 20:44:24 +0000455 Value *CurrentTop =
456 DynamicTop ? IRB.CreateLoad(StackPtrTy, DynamicTop) : StaticTop;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000457 IRB.CreateStore(CurrentTop, UnsafeStackPtr);
458 }
459
460 return DynamicTop;
461}
462
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000463void SafeStack::checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
464 AllocaInst *StackGuardSlot, Value *StackGuard) {
James Y Knight14359ef2019-02-01 20:44:24 +0000465 Value *V = IRB.CreateLoad(StackPtrTy, StackGuardSlot);
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000466 Value *Cmp = IRB.CreateICmpNE(StackGuard, V);
467
468 auto SuccessProb = BranchProbabilityInfo::getBranchProbStackProtector(true);
469 auto FailureProb = BranchProbabilityInfo::getBranchProbStackProtector(false);
470 MDNode *Weights = MDBuilder(F.getContext())
471 .createBranchWeights(SuccessProb.getNumerator(),
472 FailureProb.getNumerator());
473 Instruction *CheckTerm =
474 SplitBlockAndInsertIfThen(Cmp, &RI,
475 /* Unreachable */ true, Weights);
476 IRBuilder<> IRBFail(CheckTerm);
477 // FIXME: respect -fsanitize-trap / -ftrap-function here?
James Y Knight13680222019-02-01 02:28:03 +0000478 FunctionCallee StackChkFail =
479 F.getParent()->getOrInsertFunction("__stack_chk_fail", IRB.getVoidTy());
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000480 IRBFail.CreateCall(StackChkFail, {});
481}
482
Anna Zakscad79942016-02-02 01:03:11 +0000483/// We explicitly compute and set the unsafe stack layout for all unsafe
484/// static alloca instructions. We save the unsafe "base pointer" in the
485/// prologue into a local variable and restore it in the epilogue.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000486Value *SafeStack::moveStaticAllocasToUnsafeStack(
487 IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
Anna Zakscad79942016-02-02 01:03:11 +0000488 ArrayRef<Argument *> ByValArguments, ArrayRef<ReturnInst *> Returns,
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000489 Instruction *BasePointer, AllocaInst *StackGuardSlot) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000490 if (StaticAllocas.empty() && ByValArguments.empty())
Anna Zakscad79942016-02-02 01:03:11 +0000491 return BasePointer;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000492
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000493 DIBuilder DIB(*F.getParent());
494
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000495 StackColoring SSC(F, StaticAllocas);
496 SSC.run();
497 SSC.removeAllMarkers();
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000498
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000499 // Unsafe stack always grows down.
500 StackLayout SSL(StackAlignment);
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000501 if (StackGuardSlot) {
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000502 Type *Ty = StackGuardSlot->getAllocatedType();
503 unsigned Align =
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000504 std::max(DL.getPrefTypeAlignment(Ty), StackGuardSlot->getAlignment());
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000505 SSL.addObject(StackGuardSlot, getStaticAllocaAllocationSize(StackGuardSlot),
Evgeniy Stepanov906f6fb2016-07-26 00:05:14 +0000506 Align, SSC.getFullLiveRange());
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000507 }
508
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000509 for (Argument *Arg : ByValArguments) {
510 Type *Ty = Arg->getType()->getPointerElementType();
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000511 uint64_t Size = DL.getTypeStoreSize(Ty);
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000512 if (Size == 0)
513 Size = 1; // Don't create zero-sized stack objects.
514
515 // Ensure the object is properly aligned.
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000516 unsigned Align = std::max((unsigned)DL.getPrefTypeAlignment(Ty),
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000517 Arg->getParamAlignment());
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000518 SSL.addObject(Arg, Size, Align, SSC.getFullLiveRange());
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000519 }
520
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000521 for (AllocaInst *AI : StaticAllocas) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000522 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000523 uint64_t Size = getStaticAllocaAllocationSize(AI);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000524 if (Size == 0)
525 Size = 1; // Don't create zero-sized stack objects.
526
527 // Ensure the object is properly aligned.
528 unsigned Align =
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000529 std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000530
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000531 SSL.addObject(AI, Size, Align, SSC.getLiveRange(AI));
532 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000533
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000534 SSL.computeLayout();
535 unsigned FrameAlignment = SSL.getFrameAlignment();
536
537 // FIXME: tell SSL that we start at a less-then-MaxAlignment aligned location
538 // (AlignmentSkew).
539 if (FrameAlignment > StackAlignment) {
540 // Re-align the base pointer according to the max requested alignment.
541 assert(isPowerOf2_32(FrameAlignment));
542 IRB.SetInsertPoint(BasePointer->getNextNode());
543 BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
544 IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
545 ConstantInt::get(IntPtrTy, ~uint64_t(FrameAlignment - 1))),
546 StackPtrTy));
547 }
548
549 IRB.SetInsertPoint(BasePointer->getNextNode());
550
551 if (StackGuardSlot) {
552 unsigned Offset = SSL.getObjectOffset(StackGuardSlot);
James Y Knight77160752019-02-01 20:44:47 +0000553 Value *Off = IRB.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000554 ConstantInt::get(Int32Ty, -Offset));
555 Value *NewAI =
556 IRB.CreateBitCast(Off, StackGuardSlot->getType(), "StackGuardSlot");
557
558 // Replace alloc with the new location.
559 StackGuardSlot->replaceAllUsesWith(NewAI);
560 StackGuardSlot->eraseFromParent();
561 }
562
563 for (Argument *Arg : ByValArguments) {
564 unsigned Offset = SSL.getObjectOffset(Arg);
Daniel Neilson095d7292018-02-12 22:39:47 +0000565 unsigned Align = SSL.getObjectAlignment(Arg);
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000566 Type *Ty = Arg->getType()->getPointerElementType();
567
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000568 uint64_t Size = DL.getTypeStoreSize(Ty);
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000569 if (Size == 0)
570 Size = 1; // Don't create zero-sized stack objects.
571
James Y Knight77160752019-02-01 20:44:47 +0000572 Value *Off = IRB.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000573 ConstantInt::get(Int32Ty, -Offset));
574 Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
575 Arg->getName() + ".unsafe-byval");
576
577 // Replace alloc with the new location.
578 replaceDbgDeclare(Arg, BasePointer, BasePointer->getNextNode(), DIB,
Adrian Prantld1317012017-12-08 21:58:18 +0000579 DIExpression::NoDeref, -Offset, DIExpression::NoDeref);
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000580 Arg->replaceAllUsesWith(NewArg);
581 IRB.SetInsertPoint(cast<Instruction>(NewArg)->getNextNode());
Daniel Neilson095d7292018-02-12 22:39:47 +0000582 IRB.CreateMemCpy(Off, Align, Arg, Arg->getParamAlignment(), Size);
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000583 }
584
585 // Allocate space for every unsafe static AllocaInst on the unsafe stack.
586 for (AllocaInst *AI : StaticAllocas) {
587 IRB.SetInsertPoint(AI);
588 unsigned Offset = SSL.getObjectOffset(AI);
589
590 uint64_t Size = getStaticAllocaAllocationSize(AI);
591 if (Size == 0)
592 Size = 1; // Don't create zero-sized stack objects.
593
Adrian Prantld1317012017-12-08 21:58:18 +0000594 replaceDbgDeclareForAlloca(AI, BasePointer, DIB, DIExpression::NoDeref,
595 -Offset, DIExpression::NoDeref);
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000596 replaceDbgValueForAlloca(AI, BasePointer, DIB, -Offset);
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000597
598 // Replace uses of the alloca with the new location.
599 // Insert address calculation close to each use to work around PR27844.
600 std::string Name = std::string(AI->getName()) + ".unsafe";
601 while (!AI->use_empty()) {
602 Use &U = *AI->use_begin();
603 Instruction *User = cast<Instruction>(U.getUser());
604
605 Instruction *InsertBefore;
606 if (auto *PHI = dyn_cast<PHINode>(User))
607 InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
608 else
609 InsertBefore = User;
610
611 IRBuilder<> IRBUser(InsertBefore);
James Y Knight77160752019-02-01 20:44:47 +0000612 Value *Off = IRBUser.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000613 ConstantInt::get(Int32Ty, -Offset));
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000614 Value *Replacement = IRBUser.CreateBitCast(Off, AI->getType(), Name);
615
616 if (auto *PHI = dyn_cast<PHINode>(User)) {
617 // PHI nodes may have multiple incoming edges from the same BB (why??),
618 // all must be updated at once with the same incoming value.
619 auto *BB = PHI->getIncomingBlock(U);
620 for (unsigned I = 0; I < PHI->getNumIncomingValues(); ++I)
621 if (PHI->getIncomingBlock(I) == BB)
622 PHI->setIncomingValue(I, Replacement);
623 } else {
624 U.set(Replacement);
625 }
626 }
627
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000628 AI->eraseFromParent();
629 }
630
631 // Re-align BasePointer so that our callees would see it aligned as
632 // expected.
633 // FIXME: no need to update BasePointer in leaf functions.
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000634 unsigned FrameSize = alignTo(SSL.getFrameSize(), StackAlignment);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000635
636 // Update shadow stack pointer in the function epilogue.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000637 IRB.SetInsertPoint(BasePointer->getNextNode());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000638
639 Value *StaticTop =
James Y Knight77160752019-02-01 20:44:47 +0000640 IRB.CreateGEP(Int8Ty, BasePointer, ConstantInt::get(Int32Ty, -FrameSize),
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000641 "unsafe_stack_static_top");
642 IRB.CreateStore(StaticTop, UnsafeStackPtr);
643 return StaticTop;
644}
645
646void SafeStack::moveDynamicAllocasToUnsafeStack(
647 Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
648 ArrayRef<AllocaInst *> DynamicAllocas) {
649 DIBuilder DIB(*F.getParent());
650
651 for (AllocaInst *AI : DynamicAllocas) {
652 IRBuilder<> IRB(AI);
653
654 // Compute the new SP value (after AI).
655 Value *ArraySize = AI->getArraySize();
656 if (ArraySize->getType() != IntPtrTy)
657 ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
658
659 Type *Ty = AI->getAllocatedType();
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000660 uint64_t TySize = DL.getTypeAllocSize(Ty);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000661 Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
662
James Y Knight14359ef2019-02-01 20:44:24 +0000663 Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(StackPtrTy, UnsafeStackPtr),
664 IntPtrTy);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000665 SP = IRB.CreateSub(SP, Size);
666
667 // Align the SP value to satisfy the AllocaInst, type and stack alignments.
668 unsigned Align = std::max(
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000669 std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment()),
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000670 (unsigned)StackAlignment);
671
672 assert(isPowerOf2_32(Align));
673 Value *NewTop = IRB.CreateIntToPtr(
674 IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
675 StackPtrTy);
676
677 // Save the stack pointer.
678 IRB.CreateStore(NewTop, UnsafeStackPtr);
679 if (DynamicTop)
680 IRB.CreateStore(NewTop, DynamicTop);
681
Evgeniy Stepanov9842d612015-11-25 22:52:30 +0000682 Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000683 if (AI->hasName() && isa<Instruction>(NewAI))
684 NewAI->takeName(AI);
685
Adrian Prantld1317012017-12-08 21:58:18 +0000686 replaceDbgDeclareForAlloca(AI, NewAI, DIB, DIExpression::NoDeref, 0,
687 DIExpression::NoDeref);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000688 AI->replaceAllUsesWith(NewAI);
689 AI->eraseFromParent();
690 }
691
692 if (!DynamicAllocas.empty()) {
693 // Now go through the instructions again, replacing stacksave/stackrestore.
694 for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
695 Instruction *I = &*(It++);
696 auto II = dyn_cast<IntrinsicInst>(I);
697 if (!II)
698 continue;
699
700 if (II->getIntrinsicID() == Intrinsic::stacksave) {
701 IRBuilder<> IRB(II);
James Y Knight14359ef2019-02-01 20:44:24 +0000702 Instruction *LI = IRB.CreateLoad(StackPtrTy, UnsafeStackPtr);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000703 LI->takeName(II);
704 II->replaceAllUsesWith(LI);
705 II->eraseFromParent();
706 } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
707 IRBuilder<> IRB(II);
708 Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
709 SI->takeName(II);
710 assert(II->use_empty());
711 II->eraseFromParent();
712 }
713 }
714 }
715}
716
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000717bool SafeStack::ShouldInlinePointerAddress(CallSite &CS) {
718 Function *Callee = CS.getCalledFunction();
719 if (CS.hasFnAttr(Attribute::AlwaysInline) && isInlineViable(*Callee))
720 return true;
721 if (Callee->isInterposable() || Callee->hasFnAttribute(Attribute::NoInline) ||
722 CS.isNoInline())
723 return false;
724 return true;
725}
726
727void SafeStack::TryInlinePointerAddress() {
728 if (!isa<CallInst>(UnsafeStackPtr))
729 return;
730
Evandro Menezes7c711cc2019-04-03 21:27:03 +0000731 if(F.optForNone())
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000732 return;
733
734 CallSite CS(UnsafeStackPtr);
735 Function *Callee = CS.getCalledFunction();
736 if (!Callee || Callee->isDeclaration())
737 return;
738
739 if (!ShouldInlinePointerAddress(CS))
740 return;
741
742 InlineFunctionInfo IFI;
743 InlineFunction(CS, IFI);
744}
745
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000746bool SafeStack::run() {
747 assert(F.hasFnAttribute(Attribute::SafeStack) &&
748 "Can't run SafeStack on a function without the attribute");
749 assert(!F.isDeclaration() && "Can't run SafeStack on a function declaration");
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000750
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000751 ++NumFunctions;
752
753 SmallVector<AllocaInst *, 16> StaticAllocas;
754 SmallVector<AllocaInst *, 4> DynamicAllocas;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000755 SmallVector<Argument *, 4> ByValArguments;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000756 SmallVector<ReturnInst *, 4> Returns;
757
758 // Collect all points where stack gets unwound and needs to be restored
759 // This is only necessary because the runtime (setjmp and unwind code) is
Michael LeMay14153552016-10-17 19:09:19 +0000760 // not aware of the unsafe stack and won't unwind/restore it properly.
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000761 // To work around this problem without changing the runtime, we insert
762 // instrumentation to restore the unsafe stack pointer when necessary.
763 SmallVector<Instruction *, 4> StackRestorePoints;
764
765 // Find all static and dynamic alloca instructions that must be moved to the
766 // unsafe stack, all return instructions and stack restore points.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000767 findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
768 StackRestorePoints);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000769
770 if (StaticAllocas.empty() && DynamicAllocas.empty() &&
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000771 ByValArguments.empty() && StackRestorePoints.empty())
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000772 return false; // Nothing to do in this function.
773
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000774 if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
775 !ByValArguments.empty())
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000776 ++NumUnsafeStackFunctions; // This function has the unsafe stack.
777
778 if (!StackRestorePoints.empty())
779 ++NumUnsafeStackRestorePointsFunctions;
780
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000781 IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
Eli Friedman59de37b2018-08-24 20:42:32 +0000782 // Calls must always have a debug location, or else inlining breaks. So
783 // we explicitly set a artificial debug location here.
784 if (DISubprogram *SP = F.getSubprogram())
785 IRB.SetCurrentDebugLocation(DebugLoc::get(SP->getScopeLine(), 0, SP));
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000786 if (SafeStackUsePointerAddress) {
James Y Knight13680222019-02-01 02:28:03 +0000787 FunctionCallee Fn = F.getParent()->getOrInsertFunction(
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000788 "__safestack_pointer_address", StackPtrTy->getPointerTo(0));
789 UnsafeStackPtr = IRB.CreateCall(Fn);
790 } else {
791 UnsafeStackPtr = TL.getSafeStackPointerLocation(IRB);
792 }
Peter Collingbournede26a912015-06-22 20:26:54 +0000793
Anna Zakscad79942016-02-02 01:03:11 +0000794 // Load the current stack pointer (we'll also use it as a base pointer).
795 // FIXME: use a dedicated register for it ?
796 Instruction *BasePointer =
James Y Knight14359ef2019-02-01 20:44:24 +0000797 IRB.CreateLoad(StackPtrTy, UnsafeStackPtr, false, "unsafe_stack_ptr");
Anna Zakscad79942016-02-02 01:03:11 +0000798 assert(BasePointer->getType() == StackPtrTy);
799
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000800 AllocaInst *StackGuardSlot = nullptr;
801 // FIXME: implement weaker forms of stack protector.
802 if (F.hasFnAttribute(Attribute::StackProtect) ||
803 F.hasFnAttribute(Attribute::StackProtectStrong) ||
804 F.hasFnAttribute(Attribute::StackProtectReq)) {
805 Value *StackGuard = getStackGuard(IRB, F);
806 StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr);
807 IRB.CreateStore(StackGuard, StackGuardSlot);
808
809 for (ReturnInst *RI : Returns) {
810 IRBuilder<> IRBRet(RI);
811 checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
812 }
813 }
814
815 // The top of the unsafe stack after all unsafe static allocas are
816 // allocated.
817 Value *StaticTop =
818 moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, ByValArguments,
819 Returns, BasePointer, StackGuardSlot);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000820
821 // Safe stack object that stores the current unsafe stack top. It is updated
822 // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
823 // This is only needed if we need to restore stack pointer after longjmp
824 // or exceptions, and we have dynamic allocations.
825 // FIXME: a better alternative might be to store the unsafe stack pointer
826 // before setjmp / invoke instructions.
827 AllocaInst *DynamicTop = createStackRestorePoints(
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000828 IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000829
830 // Handle dynamic allocas.
831 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
832 DynamicAllocas);
833
Anna Zakscad79942016-02-02 01:03:11 +0000834 // Restore the unsafe stack pointer before each return.
835 for (ReturnInst *RI : Returns) {
836 IRB.SetInsertPoint(RI);
837 IRB.CreateStore(BasePointer, UnsafeStackPtr);
838 }
839
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000840 TryInlinePointerAddress();
841
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000842 LLVM_DEBUG(dbgs() << "[SafeStack] safestack applied\n");
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000843 return true;
844}
845
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000846class SafeStackLegacyPass : public FunctionPass {
Eugene Zelenko618c5552017-09-13 21:15:20 +0000847 const TargetMachine *TM = nullptr;
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000848
849public:
850 static char ID; // Pass identification, replacement for typeid..
Eugene Zelenko618c5552017-09-13 21:15:20 +0000851
852 SafeStackLegacyPass() : FunctionPass(ID) {
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000853 initializeSafeStackLegacyPassPass(*PassRegistry::getPassRegistry());
854 }
855
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000856 void getAnalysisUsage(AnalysisUsage &AU) const override {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000857 AU.addRequired<TargetPassConfig>();
Ahmed Bougacha8c358e32017-05-10 00:39:25 +0000858 AU.addRequired<TargetLibraryInfoWrapperPass>();
859 AU.addRequired<AssumptionCacheTracker>();
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000860 }
861
862 bool runOnFunction(Function &F) override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000863 LLVM_DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000864
865 if (!F.hasFnAttribute(Attribute::SafeStack)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000866 LLVM_DEBUG(dbgs() << "[SafeStack] safestack is not requested"
867 " for this function\n");
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000868 return false;
869 }
870
871 if (F.isDeclaration()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000872 LLVM_DEBUG(dbgs() << "[SafeStack] function definition"
873 " is not available\n");
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000874 return false;
875 }
876
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000877 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000878 auto *TL = TM->getSubtargetImpl(F)->getTargetLowering();
879 if (!TL)
880 report_fatal_error("TargetLowering instance is required");
881
882 auto *DL = &F.getParent()->getDataLayout();
Ahmed Bougacha8c358e32017-05-10 00:39:25 +0000883 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
884 auto &ACT = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
885
886 // Compute DT and LI only for functions that have the attribute.
887 // This is only useful because the legacy pass manager doesn't let us
888 // compute analyzes lazily.
889 // In the backend pipeline, nothing preserves DT before SafeStack, so we
890 // would otherwise always compute it wastefully, even if there is no
891 // function with the safestack attribute.
892 DominatorTree DT(F);
893 LoopInfo LI(DT);
894
895 ScalarEvolution SE(F, TLI, ACT, DT, LI);
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000896
897 return SafeStack(F, *TL, *DL, SE).run();
898 }
899};
900
Eugene Zelenko618c5552017-09-13 21:15:20 +0000901} // end anonymous namespace
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000902
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000903char SafeStackLegacyPass::ID = 0;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000904
Matthias Braun1527baa2017-05-25 21:26:32 +0000905INITIALIZE_PASS_BEGIN(SafeStackLegacyPass, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000906 "Safe Stack instrumentation pass", false, false)
907INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
Matthias Braun1527baa2017-05-25 21:26:32 +0000908INITIALIZE_PASS_END(SafeStackLegacyPass, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000909 "Safe Stack instrumentation pass", false, false)
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000910
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000911FunctionPass *llvm::createSafeStackPass() { return new SafeStackLegacyPass(); }