blob: ddbbd0f8d6e9ce611907d8d7067e01c1fdde179e [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,
Petar Jovanovice85bbf52019-05-20 10:35:57 +0000579 DIExpression::ApplyOffset, -Offset);
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
Petar Jovanovice85bbf52019-05-20 10:35:57 +0000590 replaceDbgDeclareForAlloca(AI, BasePointer, DIB, DIExpression::ApplyOffset,
591 -Offset);
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000592 replaceDbgValueForAlloca(AI, BasePointer, DIB, -Offset);
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000593
594 // Replace uses of the alloca with the new location.
595 // Insert address calculation close to each use to work around PR27844.
596 std::string Name = std::string(AI->getName()) + ".unsafe";
597 while (!AI->use_empty()) {
598 Use &U = *AI->use_begin();
599 Instruction *User = cast<Instruction>(U.getUser());
600
601 Instruction *InsertBefore;
602 if (auto *PHI = dyn_cast<PHINode>(User))
603 InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
604 else
605 InsertBefore = User;
606
607 IRBuilder<> IRBUser(InsertBefore);
James Y Knight77160752019-02-01 20:44:47 +0000608 Value *Off = IRBUser.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000609 ConstantInt::get(Int32Ty, -Offset));
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000610 Value *Replacement = IRBUser.CreateBitCast(Off, AI->getType(), Name);
611
Whitney Tsang15b7f5b2019-06-17 14:38:56 +0000612 if (auto *PHI = dyn_cast<PHINode>(User))
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000613 // PHI nodes may have multiple incoming edges from the same BB (why??),
614 // all must be updated at once with the same incoming value.
Whitney Tsang15b7f5b2019-06-17 14:38:56 +0000615 PHI->setIncomingValueForBlock(PHI->getIncomingBlock(U), Replacement);
616 else
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000617 U.set(Replacement);
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000618 }
619
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000620 AI->eraseFromParent();
621 }
622
623 // Re-align BasePointer so that our callees would see it aligned as
624 // expected.
625 // FIXME: no need to update BasePointer in leaf functions.
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000626 unsigned FrameSize = alignTo(SSL.getFrameSize(), StackAlignment);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000627
628 // Update shadow stack pointer in the function epilogue.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000629 IRB.SetInsertPoint(BasePointer->getNextNode());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000630
631 Value *StaticTop =
James Y Knight77160752019-02-01 20:44:47 +0000632 IRB.CreateGEP(Int8Ty, BasePointer, ConstantInt::get(Int32Ty, -FrameSize),
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000633 "unsafe_stack_static_top");
634 IRB.CreateStore(StaticTop, UnsafeStackPtr);
635 return StaticTop;
636}
637
638void SafeStack::moveDynamicAllocasToUnsafeStack(
639 Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
640 ArrayRef<AllocaInst *> DynamicAllocas) {
641 DIBuilder DIB(*F.getParent());
642
643 for (AllocaInst *AI : DynamicAllocas) {
644 IRBuilder<> IRB(AI);
645
646 // Compute the new SP value (after AI).
647 Value *ArraySize = AI->getArraySize();
648 if (ArraySize->getType() != IntPtrTy)
649 ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
650
651 Type *Ty = AI->getAllocatedType();
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000652 uint64_t TySize = DL.getTypeAllocSize(Ty);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000653 Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
654
James Y Knight14359ef2019-02-01 20:44:24 +0000655 Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(StackPtrTy, UnsafeStackPtr),
656 IntPtrTy);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000657 SP = IRB.CreateSub(SP, Size);
658
659 // Align the SP value to satisfy the AllocaInst, type and stack alignments.
660 unsigned Align = std::max(
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000661 std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment()),
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000662 (unsigned)StackAlignment);
663
664 assert(isPowerOf2_32(Align));
665 Value *NewTop = IRB.CreateIntToPtr(
666 IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
667 StackPtrTy);
668
669 // Save the stack pointer.
670 IRB.CreateStore(NewTop, UnsafeStackPtr);
671 if (DynamicTop)
672 IRB.CreateStore(NewTop, DynamicTop);
673
Evgeniy Stepanov9842d612015-11-25 22:52:30 +0000674 Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000675 if (AI->hasName() && isa<Instruction>(NewAI))
676 NewAI->takeName(AI);
677
Petar Jovanovice85bbf52019-05-20 10:35:57 +0000678 replaceDbgDeclareForAlloca(AI, NewAI, DIB, DIExpression::ApplyOffset, 0);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000679 AI->replaceAllUsesWith(NewAI);
680 AI->eraseFromParent();
681 }
682
683 if (!DynamicAllocas.empty()) {
684 // Now go through the instructions again, replacing stacksave/stackrestore.
685 for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
686 Instruction *I = &*(It++);
687 auto II = dyn_cast<IntrinsicInst>(I);
688 if (!II)
689 continue;
690
691 if (II->getIntrinsicID() == Intrinsic::stacksave) {
692 IRBuilder<> IRB(II);
James Y Knight14359ef2019-02-01 20:44:24 +0000693 Instruction *LI = IRB.CreateLoad(StackPtrTy, UnsafeStackPtr);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000694 LI->takeName(II);
695 II->replaceAllUsesWith(LI);
696 II->eraseFromParent();
697 } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
698 IRBuilder<> IRB(II);
699 Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
700 SI->takeName(II);
701 assert(II->use_empty());
702 II->eraseFromParent();
703 }
704 }
705 }
706}
707
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000708bool SafeStack::ShouldInlinePointerAddress(CallSite &CS) {
709 Function *Callee = CS.getCalledFunction();
710 if (CS.hasFnAttr(Attribute::AlwaysInline) && isInlineViable(*Callee))
711 return true;
712 if (Callee->isInterposable() || Callee->hasFnAttribute(Attribute::NoInline) ||
713 CS.isNoInline())
714 return false;
715 return true;
716}
717
718void SafeStack::TryInlinePointerAddress() {
719 if (!isa<CallInst>(UnsafeStackPtr))
720 return;
721
Evandro Menezes85bd3972019-04-04 22:40:06 +0000722 if(F.hasOptNone())
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000723 return;
724
725 CallSite CS(UnsafeStackPtr);
726 Function *Callee = CS.getCalledFunction();
727 if (!Callee || Callee->isDeclaration())
728 return;
729
730 if (!ShouldInlinePointerAddress(CS))
731 return;
732
733 InlineFunctionInfo IFI;
734 InlineFunction(CS, IFI);
735}
736
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000737bool SafeStack::run() {
738 assert(F.hasFnAttribute(Attribute::SafeStack) &&
739 "Can't run SafeStack on a function without the attribute");
740 assert(!F.isDeclaration() && "Can't run SafeStack on a function declaration");
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000741
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000742 ++NumFunctions;
743
744 SmallVector<AllocaInst *, 16> StaticAllocas;
745 SmallVector<AllocaInst *, 4> DynamicAllocas;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000746 SmallVector<Argument *, 4> ByValArguments;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000747 SmallVector<ReturnInst *, 4> Returns;
748
749 // Collect all points where stack gets unwound and needs to be restored
750 // This is only necessary because the runtime (setjmp and unwind code) is
Michael LeMay14153552016-10-17 19:09:19 +0000751 // not aware of the unsafe stack and won't unwind/restore it properly.
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000752 // To work around this problem without changing the runtime, we insert
753 // instrumentation to restore the unsafe stack pointer when necessary.
754 SmallVector<Instruction *, 4> StackRestorePoints;
755
756 // Find all static and dynamic alloca instructions that must be moved to the
757 // unsafe stack, all return instructions and stack restore points.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000758 findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
759 StackRestorePoints);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000760
761 if (StaticAllocas.empty() && DynamicAllocas.empty() &&
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000762 ByValArguments.empty() && StackRestorePoints.empty())
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000763 return false; // Nothing to do in this function.
764
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000765 if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
766 !ByValArguments.empty())
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000767 ++NumUnsafeStackFunctions; // This function has the unsafe stack.
768
769 if (!StackRestorePoints.empty())
770 ++NumUnsafeStackRestorePointsFunctions;
771
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000772 IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
Eli Friedman59de37b2018-08-24 20:42:32 +0000773 // Calls must always have a debug location, or else inlining breaks. So
774 // we explicitly set a artificial debug location here.
775 if (DISubprogram *SP = F.getSubprogram())
776 IRB.SetCurrentDebugLocation(DebugLoc::get(SP->getScopeLine(), 0, SP));
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000777 if (SafeStackUsePointerAddress) {
James Y Knight13680222019-02-01 02:28:03 +0000778 FunctionCallee Fn = F.getParent()->getOrInsertFunction(
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000779 "__safestack_pointer_address", StackPtrTy->getPointerTo(0));
780 UnsafeStackPtr = IRB.CreateCall(Fn);
781 } else {
782 UnsafeStackPtr = TL.getSafeStackPointerLocation(IRB);
783 }
Peter Collingbournede26a912015-06-22 20:26:54 +0000784
Anna Zakscad79942016-02-02 01:03:11 +0000785 // Load the current stack pointer (we'll also use it as a base pointer).
786 // FIXME: use a dedicated register for it ?
787 Instruction *BasePointer =
James Y Knight14359ef2019-02-01 20:44:24 +0000788 IRB.CreateLoad(StackPtrTy, UnsafeStackPtr, false, "unsafe_stack_ptr");
Anna Zakscad79942016-02-02 01:03:11 +0000789 assert(BasePointer->getType() == StackPtrTy);
790
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000791 AllocaInst *StackGuardSlot = nullptr;
792 // FIXME: implement weaker forms of stack protector.
793 if (F.hasFnAttribute(Attribute::StackProtect) ||
794 F.hasFnAttribute(Attribute::StackProtectStrong) ||
795 F.hasFnAttribute(Attribute::StackProtectReq)) {
796 Value *StackGuard = getStackGuard(IRB, F);
797 StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr);
798 IRB.CreateStore(StackGuard, StackGuardSlot);
799
800 for (ReturnInst *RI : Returns) {
801 IRBuilder<> IRBRet(RI);
802 checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
803 }
804 }
805
806 // The top of the unsafe stack after all unsafe static allocas are
807 // allocated.
808 Value *StaticTop =
809 moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, ByValArguments,
810 Returns, BasePointer, StackGuardSlot);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000811
812 // Safe stack object that stores the current unsafe stack top. It is updated
813 // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
814 // This is only needed if we need to restore stack pointer after longjmp
815 // or exceptions, and we have dynamic allocations.
816 // FIXME: a better alternative might be to store the unsafe stack pointer
817 // before setjmp / invoke instructions.
818 AllocaInst *DynamicTop = createStackRestorePoints(
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000819 IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000820
821 // Handle dynamic allocas.
822 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
823 DynamicAllocas);
824
Anna Zakscad79942016-02-02 01:03:11 +0000825 // Restore the unsafe stack pointer before each return.
826 for (ReturnInst *RI : Returns) {
827 IRB.SetInsertPoint(RI);
828 IRB.CreateStore(BasePointer, UnsafeStackPtr);
829 }
830
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000831 TryInlinePointerAddress();
832
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000833 LLVM_DEBUG(dbgs() << "[SafeStack] safestack applied\n");
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000834 return true;
835}
836
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000837class SafeStackLegacyPass : public FunctionPass {
Eugene Zelenko618c5552017-09-13 21:15:20 +0000838 const TargetMachine *TM = nullptr;
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000839
840public:
841 static char ID; // Pass identification, replacement for typeid..
Eugene Zelenko618c5552017-09-13 21:15:20 +0000842
843 SafeStackLegacyPass() : FunctionPass(ID) {
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000844 initializeSafeStackLegacyPassPass(*PassRegistry::getPassRegistry());
845 }
846
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000847 void getAnalysisUsage(AnalysisUsage &AU) const override {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000848 AU.addRequired<TargetPassConfig>();
Ahmed Bougacha8c358e32017-05-10 00:39:25 +0000849 AU.addRequired<TargetLibraryInfoWrapperPass>();
850 AU.addRequired<AssumptionCacheTracker>();
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000851 }
852
853 bool runOnFunction(Function &F) override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000854 LLVM_DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000855
856 if (!F.hasFnAttribute(Attribute::SafeStack)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000857 LLVM_DEBUG(dbgs() << "[SafeStack] safestack is not requested"
858 " for this function\n");
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000859 return false;
860 }
861
862 if (F.isDeclaration()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000863 LLVM_DEBUG(dbgs() << "[SafeStack] function definition"
864 " is not available\n");
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000865 return false;
866 }
867
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000868 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000869 auto *TL = TM->getSubtargetImpl(F)->getTargetLowering();
870 if (!TL)
871 report_fatal_error("TargetLowering instance is required");
872
873 auto *DL = &F.getParent()->getDataLayout();
Teresa Johnson9c27b592019-09-07 03:09:36 +0000874 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
Ahmed Bougacha8c358e32017-05-10 00:39:25 +0000875 auto &ACT = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
876
877 // Compute DT and LI only for functions that have the attribute.
878 // This is only useful because the legacy pass manager doesn't let us
879 // compute analyzes lazily.
880 // In the backend pipeline, nothing preserves DT before SafeStack, so we
881 // would otherwise always compute it wastefully, even if there is no
882 // function with the safestack attribute.
883 DominatorTree DT(F);
884 LoopInfo LI(DT);
885
886 ScalarEvolution SE(F, TLI, ACT, DT, LI);
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000887
888 return SafeStack(F, *TL, *DL, SE).run();
889 }
890};
891
Eugene Zelenko618c5552017-09-13 21:15:20 +0000892} // end anonymous namespace
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000893
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000894char SafeStackLegacyPass::ID = 0;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000895
Matthias Braun1527baa2017-05-25 21:26:32 +0000896INITIALIZE_PASS_BEGIN(SafeStackLegacyPass, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000897 "Safe Stack instrumentation pass", false, false)
898INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
Matthias Braun1527baa2017-05-25 21:26:32 +0000899INITIALIZE_PASS_END(SafeStackLegacyPass, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000900 "Safe Stack instrumentation pass", false, false)
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000901
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000902FunctionPass *llvm::createSafeStackPass() { return new SafeStackLegacyPass(); }