blob: 80c66ccd78181ed7b4bec12ab231d9eac2ed6086 [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 Blaikieb3bde2e2017-11-17 01:07:10 +000031#include "llvm/CodeGen/TargetLowering.h"
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +000032#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000033#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000034#include "llvm/IR/Argument.h"
35#include "llvm/IR/Attributes.h"
36#include "llvm/IR/CallSite.h"
37#include "llvm/IR/ConstantRange.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000038#include "llvm/IR/Constants.h"
Benjamin Kramer390c33c2016-01-27 16:53:42 +000039#include "llvm/IR/DIBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000040#include "llvm/IR/DataLayout.h"
41#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000042#include "llvm/IR/Dominators.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000043#include "llvm/IR/Function.h"
Benjamin Kramer390c33c2016-01-27 16:53:42 +000044#include "llvm/IR/IRBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000045#include "llvm/IR/InstIterator.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000046#include "llvm/IR/Instruction.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000047#include "llvm/IR/Instructions.h"
48#include "llvm/IR/IntrinsicInst.h"
49#include "llvm/IR/Intrinsics.h"
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +000050#include "llvm/IR/MDBuilder.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000051#include "llvm/IR/Module.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000052#include "llvm/IR/Type.h"
53#include "llvm/IR/Use.h"
54#include "llvm/IR/User.h"
55#include "llvm/IR/Value.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080056#include "llvm/InitializePasses.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"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080066#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000067#include <algorithm>
68#include <cassert>
69#include <cstdint>
70#include <string>
71#include <utility>
Peter Collingbourne82437bf2015-06-15 21:07:11 +000072
73using namespace llvm;
Evgeniy Stepanova5da2562016-06-29 20:37:43 +000074using namespace llvm::safestack;
Peter Collingbourne82437bf2015-06-15 21:07:11 +000075
Matthias Braun1527baa2017-05-25 21:26:32 +000076#define DEBUG_TYPE "safe-stack"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000077
78namespace llvm {
79
80STATISTIC(NumFunctions, "Total number of functions");
81STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
82STATISTIC(NumUnsafeStackRestorePointsFunctions,
83 "Number of functions that use setjmp or exceptions");
84
85STATISTIC(NumAllocas, "Total number of allocas");
86STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
87STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +000088STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
Peter Collingbourne82437bf2015-06-15 21:07:11 +000089STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
90
91} // namespace llvm
92
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +000093/// Use __safestack_pointer_address even if the platform has a faster way of
94/// access safe stack pointer.
95static cl::opt<bool>
96 SafeStackUsePointerAddress("safestack-use-pointer-address",
97 cl::init(false), cl::Hidden);
98
99
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000100namespace {
101
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000102/// Rewrite an SCEV expression for a memory access address to an expression that
103/// represents offset from the given alloca.
104///
105/// The implementation simply replaces all mentions of the alloca with zero.
106class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000107 const Value *AllocaPtr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000108
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000109public:
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000110 AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
111 : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000112
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000113 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000114 if (Expr->getValue() == AllocaPtr)
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000115 return SE.getZero(Expr->getType());
116 return Expr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000117 }
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000118};
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000119
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000120/// The SafeStack pass splits the stack of each function into the safe
121/// stack, which is only accessed through memory safe dereferences (as
122/// determined statically), and the unsafe stack, which contains all
123/// local variables that are accessed in ways that we can't prove to
124/// be safe.
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000125class SafeStack {
126 Function &F;
127 const TargetLoweringBase &TL;
128 const DataLayout &DL;
129 ScalarEvolution &SE;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000130
131 Type *StackPtrTy;
132 Type *IntPtrTy;
133 Type *Int32Ty;
134 Type *Int8Ty;
135
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000136 Value *UnsafeStackPtr = nullptr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000137
138 /// Unsafe stack alignment. Each stack frame must ensure that the stack is
139 /// aligned to this value. We need to re-align the unsafe stack if the
140 /// alignment of any object on the stack exceeds this value.
141 ///
142 /// 16 seems like a reasonable upper bound on the alignment of objects that we
143 /// might expect to appear on the stack on most common targets.
144 enum { StackAlignment = 16 };
145
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000146 /// Return the value of the stack canary.
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000147 Value *getStackGuard(IRBuilder<> &IRB, Function &F);
148
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000149 /// Load stack guard from the frame and check if it has changed.
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000150 void checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
151 AllocaInst *StackGuardSlot, Value *StackGuard);
152
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000153 /// Find all static allocas, dynamic allocas, return instructions and
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000154 /// stack restore points (exception unwind blocks and setjmp calls) in the
155 /// given function and append them to the respective vectors.
156 void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
157 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000158 SmallVectorImpl<Argument *> &ByValArguments,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000159 SmallVectorImpl<ReturnInst *> &Returns,
160 SmallVectorImpl<Instruction *> &StackRestorePoints);
161
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000162 /// Calculate the allocation size of a given alloca. Returns 0 if the
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000163 /// size can not be statically determined.
164 uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
165
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000166 /// Allocate space for all static allocas in \p StaticAllocas,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000167 /// replace allocas with pointers into the unsafe stack and generate code to
168 /// restore the stack pointer before all return instructions in \p Returns.
169 ///
170 /// \returns A pointer to the top of the unsafe stack after all unsafe static
171 /// allocas are allocated.
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000172 Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000173 ArrayRef<AllocaInst *> StaticAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000174 ArrayRef<Argument *> ByValArguments,
Anna Zakscad79942016-02-02 01:03:11 +0000175 ArrayRef<ReturnInst *> Returns,
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000176 Instruction *BasePointer,
177 AllocaInst *StackGuardSlot);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000178
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000179 /// Generate code to restore the stack after all stack restore points
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000180 /// in \p StackRestorePoints.
181 ///
182 /// \returns A local variable in which to maintain the dynamic top of the
183 /// unsafe stack if needed.
184 AllocaInst *
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000185 createStackRestorePoints(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000186 ArrayRef<Instruction *> StackRestorePoints,
187 Value *StaticTop, bool NeedDynamicTop);
188
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000189 /// Replace all allocas in \p DynamicAllocas with code to allocate
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000190 /// space dynamically on the unsafe stack and store the dynamic unsafe stack
191 /// top to \p DynamicTop if non-null.
192 void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
193 AllocaInst *DynamicTop,
194 ArrayRef<AllocaInst *> DynamicAllocas);
195
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000196 bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000197
198 bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000199 const Value *AllocaPtr, uint64_t AllocaSize);
200 bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
201 uint64_t AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000202
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000203 bool ShouldInlinePointerAddress(CallSite &CS);
204 void TryInlinePointerAddress();
205
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000206public:
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000207 SafeStack(Function &F, const TargetLoweringBase &TL, const DataLayout &DL,
208 ScalarEvolution &SE)
209 : F(F), TL(TL), DL(DL), SE(SE),
210 StackPtrTy(Type::getInt8PtrTy(F.getContext())),
211 IntPtrTy(DL.getIntPtrType(F.getContext())),
212 Int32Ty(Type::getInt32Ty(F.getContext())),
213 Int8Ty(Type::getInt8Ty(F.getContext())) {}
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000214
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000215 // Run the transformation on the associated function.
216 // Returns whether the function was changed.
217 bool run();
218};
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000219
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000220uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) {
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000221 uint64_t Size = DL.getTypeAllocSize(AI->getAllocatedType());
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000222 if (AI->isArrayAllocation()) {
223 auto C = dyn_cast<ConstantInt>(AI->getArraySize());
224 if (!C)
225 return 0;
226 Size *= C->getZExtValue();
227 }
228 return Size;
229}
230
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000231bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize,
232 const Value *AllocaPtr, uint64_t AllocaSize) {
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000233 AllocaOffsetRewriter Rewriter(SE, AllocaPtr);
234 const SCEV *Expr = Rewriter.visit(SE.getSCEV(Addr));
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000235
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000236 uint64_t BitWidth = SE.getTypeSizeInBits(Expr->getType());
237 ConstantRange AccessStartRange = SE.getUnsignedRange(Expr);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000238 ConstantRange SizeRange =
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000239 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize));
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000240 ConstantRange AccessRange = AccessStartRange.add(SizeRange);
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000241 ConstantRange AllocaRange =
242 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize));
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000243 bool Safe = AllocaRange.contains(AccessRange);
244
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000245 LLVM_DEBUG(
246 dbgs() << "[SafeStack] "
247 << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
248 << *AllocaPtr << "\n"
249 << " Access " << *Addr << "\n"
250 << " SCEV " << *Expr
251 << " U: " << SE.getUnsignedRange(Expr)
252 << ", S: " << SE.getSignedRange(Expr) << "\n"
253 << " Range " << AccessRange << "\n"
254 << " AllocaRange " << AllocaRange << "\n"
255 << " " << (Safe ? "safe" : "unsafe") << "\n");
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000256
257 return Safe;
258}
259
260bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000261 const Value *AllocaPtr,
262 uint64_t AllocaSize) {
Vlad Tsyrklevich2499aee2018-08-30 20:44:51 +0000263 if (auto MTI = dyn_cast<MemTransferInst>(MI)) {
264 if (MTI->getRawSource() != U && MTI->getRawDest() != U)
265 return true;
266 } else {
267 if (MI->getRawDest() != U)
268 return true;
269 }
270
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000271 const auto *Len = dyn_cast<ConstantInt>(MI->getLength());
272 // Non-constant size => unsafe. FIXME: try SCEV getRange.
273 if (!Len) return false;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000274 return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000275}
276
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000277/// Check whether a given allocation must be put on the safe
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000278/// stack or not. The function analyzes all uses of AI and checks whether it is
279/// only accessed in a memory safe way (as decided statically).
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000280bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) {
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000281 // Go through all uses of this alloca and check whether all accesses to the
282 // allocated object are statically known to be memory safe and, hence, the
283 // object can be placed on the safe stack.
284 SmallPtrSet<const Value *, 16> Visited;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000285 SmallVector<const Value *, 8> WorkList;
286 WorkList.push_back(AllocaPtr);
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000287
288 // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
289 while (!WorkList.empty()) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000290 const Value *V = WorkList.pop_back_val();
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000291 for (const Use &UI : V->uses()) {
292 auto I = cast<const Instruction>(UI.getUser());
293 assert(V == UI.get());
294
295 switch (I->getOpcode()) {
Eugene Zelenko618c5552017-09-13 21:15:20 +0000296 case Instruction::Load:
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000297 if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getType()), AllocaPtr,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000298 AllocaSize))
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000299 return false;
300 break;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000301
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000302 case Instruction::VAArg:
303 // "va-arg" from a pointer is safe.
304 break;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000305 case Instruction::Store:
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000306 if (V == I->getOperand(0)) {
307 // Stored the pointer - conservatively assume it may be unsafe.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000308 LLVM_DEBUG(dbgs()
309 << "[SafeStack] Unsafe alloca: " << *AllocaPtr
310 << "\n store of address: " << *I << "\n");
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000311 return false;
312 }
313
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000314 if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getOperand(0)->getType()),
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000315 AllocaPtr, AllocaSize))
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000316 return false;
317 break;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000318
319 case Instruction::Ret:
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000320 // Information leak.
321 return false;
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000322
323 case Instruction::Call:
324 case Instruction::Invoke: {
325 ImmutableCallSite CS(I);
326
Vedant Kumarb264d692018-12-21 21:49:40 +0000327 if (I->isLifetimeStartOrEnd())
328 continue;
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000329
330 if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000331 if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000332 LLVM_DEBUG(dbgs()
333 << "[SafeStack] Unsafe alloca: " << *AllocaPtr
334 << "\n unsafe memintrinsic: " << *I << "\n");
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000335 return false;
336 }
337 continue;
338 }
339
340 // LLVM 'nocapture' attribute is only set for arguments whose address
341 // is not stored, passed around, or used in any other non-trivial way.
342 // We assume that passing a pointer to an object as a 'nocapture
343 // readnone' argument is safe.
344 // FIXME: a more precise solution would require an interprocedural
345 // analysis here, which would look at all uses of an argument inside
346 // the function being called.
347 ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
348 for (ImmutableCallSite::arg_iterator A = B; A != E; ++A)
349 if (A->get() == V)
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000350 if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) ||
351 CS.doesNotAccessMemory()))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000352 LLVM_DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
353 << "\n unsafe call: " << *I << "\n");
Evgeniy Stepanov447bbdb2015-11-13 21:21:42 +0000354 return false;
355 }
356 continue;
357 }
358
359 default:
360 if (Visited.insert(I).second)
361 WorkList.push_back(cast<const Instruction>(I));
362 }
363 }
364 }
365
366 // All uses of the alloca are safe, we can place it on the safe stack.
367 return true;
368}
369
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000370Value *SafeStack::getStackGuard(IRBuilder<> &IRB, Function &F) {
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000371 Value *StackGuardVar = TL.getIRStackGuard(IRB);
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000372 if (!StackGuardVar)
373 StackGuardVar =
374 F.getParent()->getOrInsertGlobal("__stack_chk_guard", StackPtrTy);
James Y Knight14359ef2019-02-01 20:44:24 +0000375 return IRB.CreateLoad(StackPtrTy, StackGuardVar, "StackGuard");
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000376}
377
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000378void SafeStack::findInsts(Function &F,
379 SmallVectorImpl<AllocaInst *> &StaticAllocas,
380 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000381 SmallVectorImpl<Argument *> &ByValArguments,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000382 SmallVectorImpl<ReturnInst *> &Returns,
383 SmallVectorImpl<Instruction *> &StackRestorePoints) {
Nico Rieck78199512015-08-06 19:10:45 +0000384 for (Instruction &I : instructions(&F)) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000385 if (auto AI = dyn_cast<AllocaInst>(&I)) {
386 ++NumAllocas;
387
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000388 uint64_t Size = getStaticAllocaAllocationSize(AI);
389 if (IsSafeStackAlloca(AI, Size))
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000390 continue;
391
392 if (AI->isStaticAlloca()) {
393 ++NumUnsafeStaticAllocas;
394 StaticAllocas.push_back(AI);
395 } else {
396 ++NumUnsafeDynamicAllocas;
397 DynamicAllocas.push_back(AI);
398 }
399 } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
400 Returns.push_back(RI);
401 } else if (auto CI = dyn_cast<CallInst>(&I)) {
402 // setjmps require stack restore.
403 if (CI->getCalledFunction() && CI->canReturnTwice())
404 StackRestorePoints.push_back(CI);
405 } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
406 // Exception landing pads require stack restore.
407 StackRestorePoints.push_back(LP);
408 } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
409 if (II->getIntrinsicID() == Intrinsic::gcroot)
Eugene Zelenko618c5552017-09-13 21:15:20 +0000410 report_fatal_error(
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000411 "gcroot intrinsic not compatible with safestack attribute");
412 }
413 }
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000414 for (Argument &Arg : F.args()) {
415 if (!Arg.hasByValAttr())
416 continue;
417 uint64_t Size =
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000418 DL.getTypeStoreSize(Arg.getType()->getPointerElementType());
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000419 if (IsSafeStackAlloca(&Arg, Size))
420 continue;
421
422 ++NumUnsafeByValArguments;
423 ByValArguments.push_back(&Arg);
424 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000425}
426
427AllocaInst *
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000428SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000429 ArrayRef<Instruction *> StackRestorePoints,
430 Value *StaticTop, bool NeedDynamicTop) {
Anna Zakscad79942016-02-02 01:03:11 +0000431 assert(StaticTop && "The stack top isn't set.");
432
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000433 if (StackRestorePoints.empty())
434 return nullptr;
435
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000436 // We need the current value of the shadow stack pointer to restore
437 // after longjmp or exception catching.
438
439 // FIXME: On some platforms this could be handled by the longjmp/exception
440 // runtime itself.
441
442 AllocaInst *DynamicTop = nullptr;
Anna Zakscad79942016-02-02 01:03:11 +0000443 if (NeedDynamicTop) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000444 // If we also have dynamic alloca's, the stack pointer value changes
445 // throughout the function. For now we store it in an alloca.
446 DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
447 "unsafe_stack_dynamic_ptr");
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000448 IRB.CreateStore(StaticTop, DynamicTop);
Anna Zakscad79942016-02-02 01:03:11 +0000449 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000450
451 // Restore current stack pointer after longjmp/exception catch.
452 for (Instruction *I : StackRestorePoints) {
453 ++NumUnsafeStackRestorePoints;
454
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000455 IRB.SetInsertPoint(I->getNextNode());
James Y Knight14359ef2019-02-01 20:44:24 +0000456 Value *CurrentTop =
457 DynamicTop ? IRB.CreateLoad(StackPtrTy, DynamicTop) : StaticTop;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000458 IRB.CreateStore(CurrentTop, UnsafeStackPtr);
459 }
460
461 return DynamicTop;
462}
463
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000464void SafeStack::checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
465 AllocaInst *StackGuardSlot, Value *StackGuard) {
James Y Knight14359ef2019-02-01 20:44:24 +0000466 Value *V = IRB.CreateLoad(StackPtrTy, StackGuardSlot);
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000467 Value *Cmp = IRB.CreateICmpNE(StackGuard, V);
468
469 auto SuccessProb = BranchProbabilityInfo::getBranchProbStackProtector(true);
470 auto FailureProb = BranchProbabilityInfo::getBranchProbStackProtector(false);
471 MDNode *Weights = MDBuilder(F.getContext())
472 .createBranchWeights(SuccessProb.getNumerator(),
473 FailureProb.getNumerator());
474 Instruction *CheckTerm =
475 SplitBlockAndInsertIfThen(Cmp, &RI,
476 /* Unreachable */ true, Weights);
477 IRBuilder<> IRBFail(CheckTerm);
478 // FIXME: respect -fsanitize-trap / -ftrap-function here?
James Y Knight13680222019-02-01 02:28:03 +0000479 FunctionCallee StackChkFail =
480 F.getParent()->getOrInsertFunction("__stack_chk_fail", IRB.getVoidTy());
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000481 IRBFail.CreateCall(StackChkFail, {});
482}
483
Anna Zakscad79942016-02-02 01:03:11 +0000484/// We explicitly compute and set the unsafe stack layout for all unsafe
485/// static alloca instructions. We save the unsafe "base pointer" in the
486/// prologue into a local variable and restore it in the epilogue.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000487Value *SafeStack::moveStaticAllocasToUnsafeStack(
488 IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
Anna Zakscad79942016-02-02 01:03:11 +0000489 ArrayRef<Argument *> ByValArguments, ArrayRef<ReturnInst *> Returns,
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000490 Instruction *BasePointer, AllocaInst *StackGuardSlot) {
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000491 if (StaticAllocas.empty() && ByValArguments.empty())
Anna Zakscad79942016-02-02 01:03:11 +0000492 return BasePointer;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000493
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000494 DIBuilder DIB(*F.getParent());
495
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000496 StackColoring SSC(F, StaticAllocas);
497 SSC.run();
498 SSC.removeAllMarkers();
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000499
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000500 // Unsafe stack always grows down.
501 StackLayout SSL(StackAlignment);
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000502 if (StackGuardSlot) {
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000503 Type *Ty = StackGuardSlot->getAllocatedType();
504 unsigned Align =
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000505 std::max(DL.getPrefTypeAlignment(Ty), StackGuardSlot->getAlignment());
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000506 SSL.addObject(StackGuardSlot, getStaticAllocaAllocationSize(StackGuardSlot),
Evgeniy Stepanov906f6fb2016-07-26 00:05:14 +0000507 Align, SSC.getFullLiveRange());
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000508 }
509
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000510 for (Argument *Arg : ByValArguments) {
511 Type *Ty = Arg->getType()->getPointerElementType();
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000512 uint64_t Size = DL.getTypeStoreSize(Ty);
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000513 if (Size == 0)
514 Size = 1; // Don't create zero-sized stack objects.
515
516 // Ensure the object is properly aligned.
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000517 unsigned Align = std::max((unsigned)DL.getPrefTypeAlignment(Ty),
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000518 Arg->getParamAlignment());
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000519 SSL.addObject(Arg, Size, Align, SSC.getFullLiveRange());
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000520 }
521
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000522 for (AllocaInst *AI : StaticAllocas) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000523 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanova4ac3f42015-12-01 00:06:13 +0000524 uint64_t Size = getStaticAllocaAllocationSize(AI);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000525 if (Size == 0)
526 Size = 1; // Don't create zero-sized stack objects.
527
528 // Ensure the object is properly aligned.
529 unsigned Align =
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000530 std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000531
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000532 SSL.addObject(AI, Size, Align, SSC.getLiveRange(AI));
533 }
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000534
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000535 SSL.computeLayout();
536 unsigned FrameAlignment = SSL.getFrameAlignment();
537
538 // FIXME: tell SSL that we start at a less-then-MaxAlignment aligned location
539 // (AlignmentSkew).
540 if (FrameAlignment > StackAlignment) {
541 // Re-align the base pointer according to the max requested alignment.
542 assert(isPowerOf2_32(FrameAlignment));
543 IRB.SetInsertPoint(BasePointer->getNextNode());
544 BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
545 IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
546 ConstantInt::get(IntPtrTy, ~uint64_t(FrameAlignment - 1))),
547 StackPtrTy));
548 }
549
550 IRB.SetInsertPoint(BasePointer->getNextNode());
551
552 if (StackGuardSlot) {
553 unsigned Offset = SSL.getObjectOffset(StackGuardSlot);
James Y Knight77160752019-02-01 20:44:47 +0000554 Value *Off = IRB.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000555 ConstantInt::get(Int32Ty, -Offset));
556 Value *NewAI =
557 IRB.CreateBitCast(Off, StackGuardSlot->getType(), "StackGuardSlot");
558
559 // Replace alloc with the new location.
560 StackGuardSlot->replaceAllUsesWith(NewAI);
561 StackGuardSlot->eraseFromParent();
562 }
563
564 for (Argument *Arg : ByValArguments) {
565 unsigned Offset = SSL.getObjectOffset(Arg);
Daniel Neilson095d7292018-02-12 22:39:47 +0000566 unsigned Align = SSL.getObjectAlignment(Arg);
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000567 Type *Ty = Arg->getType()->getPointerElementType();
568
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000569 uint64_t Size = DL.getTypeStoreSize(Ty);
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000570 if (Size == 0)
571 Size = 1; // Don't create zero-sized stack objects.
572
James Y Knight77160752019-02-01 20:44:47 +0000573 Value *Off = IRB.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000574 ConstantInt::get(Int32Ty, -Offset));
575 Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
576 Arg->getName() + ".unsafe-byval");
577
578 // Replace alloc with the new location.
579 replaceDbgDeclare(Arg, BasePointer, BasePointer->getNextNode(), DIB,
Petar Jovanovice85bbf52019-05-20 10:35:57 +0000580 DIExpression::ApplyOffset, -Offset);
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000581 Arg->replaceAllUsesWith(NewArg);
582 IRB.SetInsertPoint(cast<Instruction>(NewArg)->getNextNode());
Daniel Neilson095d7292018-02-12 22:39:47 +0000583 IRB.CreateMemCpy(Off, Align, Arg, Arg->getParamAlignment(), Size);
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000584 }
585
586 // Allocate space for every unsafe static AllocaInst on the unsafe stack.
587 for (AllocaInst *AI : StaticAllocas) {
588 IRB.SetInsertPoint(AI);
589 unsigned Offset = SSL.getObjectOffset(AI);
590
Petar Jovanovice85bbf52019-05-20 10:35:57 +0000591 replaceDbgDeclareForAlloca(AI, BasePointer, DIB, DIExpression::ApplyOffset,
592 -Offset);
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000593 replaceDbgValueForAlloca(AI, BasePointer, DIB, -Offset);
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000594
595 // Replace uses of the alloca with the new location.
596 // Insert address calculation close to each use to work around PR27844.
597 std::string Name = std::string(AI->getName()) + ".unsafe";
598 while (!AI->use_empty()) {
599 Use &U = *AI->use_begin();
600 Instruction *User = cast<Instruction>(U.getUser());
601
602 Instruction *InsertBefore;
603 if (auto *PHI = dyn_cast<PHINode>(User))
604 InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
605 else
606 InsertBefore = User;
607
608 IRBuilder<> IRBUser(InsertBefore);
James Y Knight77160752019-02-01 20:44:47 +0000609 Value *Off = IRBUser.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000610 ConstantInt::get(Int32Ty, -Offset));
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000611 Value *Replacement = IRBUser.CreateBitCast(Off, AI->getType(), Name);
612
Whitney Tsang15b7f5b2019-06-17 14:38:56 +0000613 if (auto *PHI = dyn_cast<PHINode>(User))
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000614 // PHI nodes may have multiple incoming edges from the same BB (why??),
615 // all must be updated at once with the same incoming value.
Whitney Tsang15b7f5b2019-06-17 14:38:56 +0000616 PHI->setIncomingValueForBlock(PHI->getIncomingBlock(U), Replacement);
617 else
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000618 U.set(Replacement);
Evgeniy Stepanov45fa0fd2016-06-16 22:34:04 +0000619 }
620
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000621 AI->eraseFromParent();
622 }
623
624 // Re-align BasePointer so that our callees would see it aligned as
625 // expected.
626 // FIXME: no need to update BasePointer in leaf functions.
Evgeniy Stepanova5da2562016-06-29 20:37:43 +0000627 unsigned FrameSize = alignTo(SSL.getFrameSize(), StackAlignment);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000628
629 // Update shadow stack pointer in the function epilogue.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000630 IRB.SetInsertPoint(BasePointer->getNextNode());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000631
632 Value *StaticTop =
James Y Knight77160752019-02-01 20:44:47 +0000633 IRB.CreateGEP(Int8Ty, BasePointer, ConstantInt::get(Int32Ty, -FrameSize),
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000634 "unsafe_stack_static_top");
635 IRB.CreateStore(StaticTop, UnsafeStackPtr);
636 return StaticTop;
637}
638
639void SafeStack::moveDynamicAllocasToUnsafeStack(
640 Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
641 ArrayRef<AllocaInst *> DynamicAllocas) {
642 DIBuilder DIB(*F.getParent());
643
644 for (AllocaInst *AI : DynamicAllocas) {
645 IRBuilder<> IRB(AI);
646
647 // Compute the new SP value (after AI).
648 Value *ArraySize = AI->getArraySize();
649 if (ArraySize->getType() != IntPtrTy)
650 ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
651
652 Type *Ty = AI->getAllocatedType();
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000653 uint64_t TySize = DL.getTypeAllocSize(Ty);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000654 Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
655
James Y Knight14359ef2019-02-01 20:44:24 +0000656 Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(StackPtrTy, UnsafeStackPtr),
657 IntPtrTy);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000658 SP = IRB.CreateSub(SP, Size);
659
660 // Align the SP value to satisfy the AllocaInst, type and stack alignments.
661 unsigned Align = std::max(
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000662 std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment()),
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000663 (unsigned)StackAlignment);
664
665 assert(isPowerOf2_32(Align));
666 Value *NewTop = IRB.CreateIntToPtr(
667 IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
668 StackPtrTy);
669
670 // Save the stack pointer.
671 IRB.CreateStore(NewTop, UnsafeStackPtr);
672 if (DynamicTop)
673 IRB.CreateStore(NewTop, DynamicTop);
674
Evgeniy Stepanov9842d612015-11-25 22:52:30 +0000675 Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000676 if (AI->hasName() && isa<Instruction>(NewAI))
677 NewAI->takeName(AI);
678
Petar Jovanovice85bbf52019-05-20 10:35:57 +0000679 replaceDbgDeclareForAlloca(AI, NewAI, DIB, DIExpression::ApplyOffset, 0);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000680 AI->replaceAllUsesWith(NewAI);
681 AI->eraseFromParent();
682 }
683
684 if (!DynamicAllocas.empty()) {
685 // Now go through the instructions again, replacing stacksave/stackrestore.
686 for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
687 Instruction *I = &*(It++);
688 auto II = dyn_cast<IntrinsicInst>(I);
689 if (!II)
690 continue;
691
692 if (II->getIntrinsicID() == Intrinsic::stacksave) {
693 IRBuilder<> IRB(II);
James Y Knight14359ef2019-02-01 20:44:24 +0000694 Instruction *LI = IRB.CreateLoad(StackPtrTy, UnsafeStackPtr);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000695 LI->takeName(II);
696 II->replaceAllUsesWith(LI);
697 II->eraseFromParent();
698 } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
699 IRBuilder<> IRB(II);
700 Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
701 SI->takeName(II);
702 assert(II->use_empty());
703 II->eraseFromParent();
704 }
705 }
706 }
707}
708
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000709bool SafeStack::ShouldInlinePointerAddress(CallSite &CS) {
710 Function *Callee = CS.getCalledFunction();
711 if (CS.hasFnAttr(Attribute::AlwaysInline) && isInlineViable(*Callee))
712 return true;
713 if (Callee->isInterposable() || Callee->hasFnAttribute(Attribute::NoInline) ||
714 CS.isNoInline())
715 return false;
716 return true;
717}
718
719void SafeStack::TryInlinePointerAddress() {
720 if (!isa<CallInst>(UnsafeStackPtr))
721 return;
722
Evandro Menezes85bd3972019-04-04 22:40:06 +0000723 if(F.hasOptNone())
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000724 return;
725
726 CallSite CS(UnsafeStackPtr);
727 Function *Callee = CS.getCalledFunction();
728 if (!Callee || Callee->isDeclaration())
729 return;
730
731 if (!ShouldInlinePointerAddress(CS))
732 return;
733
734 InlineFunctionInfo IFI;
735 InlineFunction(CS, IFI);
736}
737
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000738bool SafeStack::run() {
739 assert(F.hasFnAttribute(Attribute::SafeStack) &&
740 "Can't run SafeStack on a function without the attribute");
741 assert(!F.isDeclaration() && "Can't run SafeStack on a function declaration");
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000742
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000743 ++NumFunctions;
744
745 SmallVector<AllocaInst *, 16> StaticAllocas;
746 SmallVector<AllocaInst *, 4> DynamicAllocas;
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000747 SmallVector<Argument *, 4> ByValArguments;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000748 SmallVector<ReturnInst *, 4> Returns;
749
750 // Collect all points where stack gets unwound and needs to be restored
751 // This is only necessary because the runtime (setjmp and unwind code) is
Michael LeMay14153552016-10-17 19:09:19 +0000752 // not aware of the unsafe stack and won't unwind/restore it properly.
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000753 // To work around this problem without changing the runtime, we insert
754 // instrumentation to restore the unsafe stack pointer when necessary.
755 SmallVector<Instruction *, 4> StackRestorePoints;
756
757 // Find all static and dynamic alloca instructions that must be moved to the
758 // unsafe stack, all return instructions and stack restore points.
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000759 findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
760 StackRestorePoints);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000761
762 if (StaticAllocas.empty() && DynamicAllocas.empty() &&
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000763 ByValArguments.empty() && StackRestorePoints.empty())
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000764 return false; // Nothing to do in this function.
765
Evgeniy Stepanov42f3b122015-12-01 00:40:05 +0000766 if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
767 !ByValArguments.empty())
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000768 ++NumUnsafeStackFunctions; // This function has the unsafe stack.
769
770 if (!StackRestorePoints.empty())
771 ++NumUnsafeStackRestorePointsFunctions;
772
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000773 IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
Eli Friedman59de37b2018-08-24 20:42:32 +0000774 // Calls must always have a debug location, or else inlining breaks. So
775 // we explicitly set a artificial debug location here.
776 if (DISubprogram *SP = F.getSubprogram())
777 IRB.SetCurrentDebugLocation(DebugLoc::get(SP->getScopeLine(), 0, SP));
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000778 if (SafeStackUsePointerAddress) {
James Y Knight13680222019-02-01 02:28:03 +0000779 FunctionCallee Fn = F.getParent()->getOrInsertFunction(
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000780 "__safestack_pointer_address", StackPtrTy->getPointerTo(0));
781 UnsafeStackPtr = IRB.CreateCall(Fn);
782 } else {
783 UnsafeStackPtr = TL.getSafeStackPointerLocation(IRB);
784 }
Peter Collingbournede26a912015-06-22 20:26:54 +0000785
Anna Zakscad79942016-02-02 01:03:11 +0000786 // Load the current stack pointer (we'll also use it as a base pointer).
787 // FIXME: use a dedicated register for it ?
788 Instruction *BasePointer =
James Y Knight14359ef2019-02-01 20:44:24 +0000789 IRB.CreateLoad(StackPtrTy, UnsafeStackPtr, false, "unsafe_stack_ptr");
Anna Zakscad79942016-02-02 01:03:11 +0000790 assert(BasePointer->getType() == StackPtrTy);
791
Evgeniy Stepanovf17120a2016-04-11 22:27:48 +0000792 AllocaInst *StackGuardSlot = nullptr;
793 // FIXME: implement weaker forms of stack protector.
794 if (F.hasFnAttribute(Attribute::StackProtect) ||
795 F.hasFnAttribute(Attribute::StackProtectStrong) ||
796 F.hasFnAttribute(Attribute::StackProtectReq)) {
797 Value *StackGuard = getStackGuard(IRB, F);
798 StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr);
799 IRB.CreateStore(StackGuard, StackGuardSlot);
800
801 for (ReturnInst *RI : Returns) {
802 IRBuilder<> IRBRet(RI);
803 checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
804 }
805 }
806
807 // The top of the unsafe stack after all unsafe static allocas are
808 // allocated.
809 Value *StaticTop =
810 moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, ByValArguments,
811 Returns, BasePointer, StackGuardSlot);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000812
813 // Safe stack object that stores the current unsafe stack top. It is updated
814 // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
815 // This is only needed if we need to restore stack pointer after longjmp
816 // or exceptions, and we have dynamic allocations.
817 // FIXME: a better alternative might be to store the unsafe stack pointer
818 // before setjmp / invoke instructions.
819 AllocaInst *DynamicTop = createStackRestorePoints(
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000820 IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000821
822 // Handle dynamic allocas.
823 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
824 DynamicAllocas);
825
Anna Zakscad79942016-02-02 01:03:11 +0000826 // Restore the unsafe stack pointer before each return.
827 for (ReturnInst *RI : Returns) {
828 IRB.SetInsertPoint(RI);
829 IRB.CreateStore(BasePointer, UnsafeStackPtr);
830 }
831
Evgeniy Stepanovd5a6fdb2018-01-23 21:27:07 +0000832 TryInlinePointerAddress();
833
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000834 LLVM_DEBUG(dbgs() << "[SafeStack] safestack applied\n");
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000835 return true;
836}
837
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000838class SafeStackLegacyPass : public FunctionPass {
Eugene Zelenko618c5552017-09-13 21:15:20 +0000839 const TargetMachine *TM = nullptr;
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000840
841public:
842 static char ID; // Pass identification, replacement for typeid..
Eugene Zelenko618c5552017-09-13 21:15:20 +0000843
844 SafeStackLegacyPass() : FunctionPass(ID) {
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000845 initializeSafeStackLegacyPassPass(*PassRegistry::getPassRegistry());
846 }
847
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000848 void getAnalysisUsage(AnalysisUsage &AU) const override {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000849 AU.addRequired<TargetPassConfig>();
Ahmed Bougacha8c358e32017-05-10 00:39:25 +0000850 AU.addRequired<TargetLibraryInfoWrapperPass>();
851 AU.addRequired<AssumptionCacheTracker>();
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000852 }
853
854 bool runOnFunction(Function &F) override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000855 LLVM_DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000856
857 if (!F.hasFnAttribute(Attribute::SafeStack)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000858 LLVM_DEBUG(dbgs() << "[SafeStack] safestack is not requested"
859 " for this function\n");
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000860 return false;
861 }
862
863 if (F.isDeclaration()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000864 LLVM_DEBUG(dbgs() << "[SafeStack] function definition"
865 " is not available\n");
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000866 return false;
867 }
868
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000869 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000870 auto *TL = TM->getSubtargetImpl(F)->getTargetLowering();
871 if (!TL)
872 report_fatal_error("TargetLowering instance is required");
873
874 auto *DL = &F.getParent()->getDataLayout();
Teresa Johnson9c27b592019-09-07 03:09:36 +0000875 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
Ahmed Bougacha8c358e32017-05-10 00:39:25 +0000876 auto &ACT = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
877
878 // Compute DT and LI only for functions that have the attribute.
879 // This is only useful because the legacy pass manager doesn't let us
880 // compute analyzes lazily.
881 // In the backend pipeline, nothing preserves DT before SafeStack, so we
882 // would otherwise always compute it wastefully, even if there is no
883 // function with the safestack attribute.
884 DominatorTree DT(F);
885 LoopInfo LI(DT);
886
887 ScalarEvolution SE(F, TLI, ACT, DT, LI);
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000888
889 return SafeStack(F, *TL, *DL, SE).run();
890 }
891};
892
Eugene Zelenko618c5552017-09-13 21:15:20 +0000893} // end anonymous namespace
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000894
Ahmed Bougacha00d68222017-05-10 00:39:22 +0000895char SafeStackLegacyPass::ID = 0;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000896
Matthias Braun1527baa2017-05-25 21:26:32 +0000897INITIALIZE_PASS_BEGIN(SafeStackLegacyPass, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000898 "Safe Stack instrumentation pass", false, false)
899INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
Matthias Braun1527baa2017-05-25 21:26:32 +0000900INITIALIZE_PASS_END(SafeStackLegacyPass, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000901 "Safe Stack instrumentation pass", false, false)
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000902
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000903FunctionPass *llvm::createSafeStackPass() { return new SafeStackLegacyPass(); }