blob: d351358b463595a30e27afc92f7082330cdf18d1 [file] [log] [blame]
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001//===-- SafeStack.cpp - Safe Stack Insertion ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass splits the stack into the safe stack (kept as-is for LLVM backend)
11// and the unsafe stack (explicitly allocated and managed through the runtime
12// support library).
13//
14// http://clang.llvm.org/docs/SafeStack.html
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/Transforms/Instrumentation.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/Triple.h"
21#include "llvm/Analysis/AliasAnalysis.h"
Evgeniy Stepanova2002b02015-09-23 18:07:56 +000022#include "llvm/CodeGen/Passes.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/DIBuilder.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/InstIterator.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/Module.h"
34#include "llvm/Pass.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/Format.h"
38#include "llvm/Support/MathExtras.h"
39#include "llvm/Support/raw_os_ostream.h"
Evgeniy Stepanova2002b02015-09-23 18:07:56 +000040#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetSubtargetInfo.h"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000042#include "llvm/Transforms/Utils/Local.h"
43#include "llvm/Transforms/Utils/ModuleUtils.h"
44
45using namespace llvm;
46
47#define DEBUG_TYPE "safestack"
48
49namespace llvm {
50
51STATISTIC(NumFunctions, "Total number of functions");
52STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
53STATISTIC(NumUnsafeStackRestorePointsFunctions,
54 "Number of functions that use setjmp or exceptions");
55
56STATISTIC(NumAllocas, "Total number of allocas");
57STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
58STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
59STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
60
61} // namespace llvm
62
63namespace {
64
65/// Check whether a given alloca instruction (AI) should be put on the safe
66/// stack or not. The function analyzes all uses of AI and checks whether it is
67/// only accessed in a memory safe way (as decided statically).
68bool IsSafeStackAlloca(const AllocaInst *AI) {
69 // Go through all uses of this alloca and check whether all accesses to the
70 // allocated object are statically known to be memory safe and, hence, the
71 // object can be placed on the safe stack.
72
73 SmallPtrSet<const Value *, 16> Visited;
74 SmallVector<const Instruction *, 8> WorkList;
75 WorkList.push_back(AI);
76
77 // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
78 while (!WorkList.empty()) {
79 const Instruction *V = WorkList.pop_back_val();
80 for (const Use &UI : V->uses()) {
81 auto I = cast<const Instruction>(UI.getUser());
82 assert(V == UI.get());
83
84 switch (I->getOpcode()) {
85 case Instruction::Load:
86 // Loading from a pointer is safe.
87 break;
88 case Instruction::VAArg:
89 // "va-arg" from a pointer is safe.
90 break;
91 case Instruction::Store:
92 if (V == I->getOperand(0))
93 // Stored the pointer - conservatively assume it may be unsafe.
94 return false;
95 // Storing to the pointee is safe.
96 break;
97
98 case Instruction::GetElementPtr:
99 if (!cast<const GetElementPtrInst>(I)->hasAllConstantIndices())
100 // GEP with non-constant indices can lead to memory errors.
101 // This also applies to inbounds GEPs, as the inbounds attribute
102 // represents an assumption that the address is in bounds, rather than
103 // an assertion that it is.
104 return false;
105
106 // We assume that GEP on static alloca with constant indices is safe,
107 // otherwise a compiler would detect it and warn during compilation.
108
109 if (!isa<const ConstantInt>(AI->getArraySize()))
110 // However, if the array size itself is not constant, the access
111 // might still be unsafe at runtime.
112 return false;
113
114 /* fallthrough */
115
116 case Instruction::BitCast:
117 case Instruction::IntToPtr:
118 case Instruction::PHI:
119 case Instruction::PtrToInt:
120 case Instruction::Select:
121 // The object can be safe or not, depending on how the result of the
122 // instruction is used.
123 if (Visited.insert(I).second)
124 WorkList.push_back(cast<const Instruction>(I));
125 break;
126
127 case Instruction::Call:
128 case Instruction::Invoke: {
129 // FIXME: add support for memset and memcpy intrinsics.
130 ImmutableCallSite CS(I);
131
132 // LLVM 'nocapture' attribute is only set for arguments whose address
133 // is not stored, passed around, or used in any other non-trivial way.
134 // We assume that passing a pointer to an object as a 'nocapture'
135 // argument is safe.
136 // FIXME: a more precise solution would require an interprocedural
137 // analysis here, which would look at all uses of an argument inside
138 // the function being called.
139 ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
140 for (ImmutableCallSite::arg_iterator A = B; A != E; ++A)
141 if (A->get() == V && !CS.doesNotCapture(A - B))
142 // The parameter is not marked 'nocapture' - unsafe.
143 return false;
144 continue;
145 }
146
147 default:
148 // The object is unsafe if it is used in any other way.
149 return false;
150 }
151 }
152 }
153
154 // All uses of the alloca are safe, we can place it on the safe stack.
155 return true;
156}
157
158/// The SafeStack pass splits the stack of each function into the
159/// safe stack, which is only accessed through memory safe dereferences
160/// (as determined statically), and the unsafe stack, which contains all
161/// local variables that are accessed in unsafe ways.
162class SafeStack : public FunctionPass {
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000163 const TargetMachine *TM;
164 const TargetLoweringBase *TLI;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000165 const DataLayout *DL;
166
167 Type *StackPtrTy;
168 Type *IntPtrTy;
169 Type *Int32Ty;
170 Type *Int8Ty;
171
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000172 Value *UnsafeStackPtr = nullptr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000173
174 /// Unsafe stack alignment. Each stack frame must ensure that the stack is
175 /// aligned to this value. We need to re-align the unsafe stack if the
176 /// alignment of any object on the stack exceeds this value.
177 ///
178 /// 16 seems like a reasonable upper bound on the alignment of objects that we
179 /// might expect to appear on the stack on most common targets.
180 enum { StackAlignment = 16 };
181
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000182 /// \brief Build a value representing a pointer to the unsafe stack pointer.
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000183 Value *getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F);
184
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000185 /// \brief Find all static allocas, dynamic allocas, return instructions and
186 /// stack restore points (exception unwind blocks and setjmp calls) in the
187 /// given function and append them to the respective vectors.
188 void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
189 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
190 SmallVectorImpl<ReturnInst *> &Returns,
191 SmallVectorImpl<Instruction *> &StackRestorePoints);
192
193 /// \brief Allocate space for all static allocas in \p StaticAllocas,
194 /// replace allocas with pointers into the unsafe stack and generate code to
195 /// restore the stack pointer before all return instructions in \p Returns.
196 ///
197 /// \returns A pointer to the top of the unsafe stack after all unsafe static
198 /// allocas are allocated.
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000199 Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000200 ArrayRef<AllocaInst *> StaticAllocas,
201 ArrayRef<ReturnInst *> Returns);
202
203 /// \brief Generate code to restore the stack after all stack restore points
204 /// in \p StackRestorePoints.
205 ///
206 /// \returns A local variable in which to maintain the dynamic top of the
207 /// unsafe stack if needed.
208 AllocaInst *
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000209 createStackRestorePoints(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000210 ArrayRef<Instruction *> StackRestorePoints,
211 Value *StaticTop, bool NeedDynamicTop);
212
213 /// \brief Replace all allocas in \p DynamicAllocas with code to allocate
214 /// space dynamically on the unsafe stack and store the dynamic unsafe stack
215 /// top to \p DynamicTop if non-null.
216 void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
217 AllocaInst *DynamicTop,
218 ArrayRef<AllocaInst *> DynamicAllocas);
219
220public:
221 static char ID; // Pass identification, replacement for typeid.
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000222 SafeStack(const TargetMachine *TM)
223 : FunctionPass(ID), TM(TM), TLI(nullptr), DL(nullptr) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000224 initializeSafeStackPass(*PassRegistry::getPassRegistry());
225 }
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000226 SafeStack() : SafeStack(nullptr) {}
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000227
Hans Wennborgaa15bff2015-09-10 16:49:58 +0000228 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000229 AU.addRequired<AAResultsWrapperPass>();
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000230 }
231
Hans Wennborgaa15bff2015-09-10 16:49:58 +0000232 bool doInitialization(Module &M) override {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000233 DL = &M.getDataLayout();
234
235 StackPtrTy = Type::getInt8PtrTy(M.getContext());
236 IntPtrTy = DL->getIntPtrType(M.getContext());
237 Int32Ty = Type::getInt32Ty(M.getContext());
238 Int8Ty = Type::getInt8Ty(M.getContext());
239
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000240 return false;
241 }
242
Hans Wennborgaa15bff2015-09-10 16:49:58 +0000243 bool runOnFunction(Function &F) override;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000244}; // class SafeStack
245
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000246Value *SafeStack::getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F) {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000247 // Check if there is a target-specific location for the unsafe stack pointer.
248 if (TLI)
249 if (Value *V = TLI->getSafeStackPointerLocation(IRB))
250 return V;
251
252 // Otherwise, assume the target links with compiler-rt, which provides a
253 // thread-local variable with a magic name.
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000254 Module &M = *F.getParent();
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000255 const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
256 auto UnsafeStackPtr =
257 dyn_cast_or_null<GlobalVariable>(M.getNamedValue(UnsafeStackPtrVar));
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000258
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000259 if (!UnsafeStackPtr) {
260 // The global variable is not defined yet, define it ourselves.
261 // We use the initial-exec TLS model because we do not support the
262 // variable living anywhere other than in the main executable.
263 UnsafeStackPtr = new GlobalVariable(
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000264 M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000265 UnsafeStackPtrVar, nullptr, GlobalValue::InitialExecTLSModel);
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000266 } else {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000267 // The variable exists, check its type and attributes.
268 if (UnsafeStackPtr->getValueType() != StackPtrTy)
269 report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
270 if (!UnsafeStackPtr->isThreadLocal())
271 report_fatal_error(Twine(UnsafeStackPtrVar) + " must be thread-local");
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000272 }
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +0000273 return UnsafeStackPtr;
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000274}
275
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000276void SafeStack::findInsts(Function &F,
277 SmallVectorImpl<AllocaInst *> &StaticAllocas,
278 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
279 SmallVectorImpl<ReturnInst *> &Returns,
280 SmallVectorImpl<Instruction *> &StackRestorePoints) {
Nico Rieck78199512015-08-06 19:10:45 +0000281 for (Instruction &I : instructions(&F)) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000282 if (auto AI = dyn_cast<AllocaInst>(&I)) {
283 ++NumAllocas;
284
285 if (IsSafeStackAlloca(AI))
286 continue;
287
288 if (AI->isStaticAlloca()) {
289 ++NumUnsafeStaticAllocas;
290 StaticAllocas.push_back(AI);
291 } else {
292 ++NumUnsafeDynamicAllocas;
293 DynamicAllocas.push_back(AI);
294 }
295 } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
296 Returns.push_back(RI);
297 } else if (auto CI = dyn_cast<CallInst>(&I)) {
298 // setjmps require stack restore.
299 if (CI->getCalledFunction() && CI->canReturnTwice())
300 StackRestorePoints.push_back(CI);
301 } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
302 // Exception landing pads require stack restore.
303 StackRestorePoints.push_back(LP);
304 } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
305 if (II->getIntrinsicID() == Intrinsic::gcroot)
306 llvm::report_fatal_error(
307 "gcroot intrinsic not compatible with safestack attribute");
308 }
309 }
310}
311
312AllocaInst *
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000313SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000314 ArrayRef<Instruction *> StackRestorePoints,
315 Value *StaticTop, bool NeedDynamicTop) {
316 if (StackRestorePoints.empty())
317 return nullptr;
318
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000319 // We need the current value of the shadow stack pointer to restore
320 // after longjmp or exception catching.
321
322 // FIXME: On some platforms this could be handled by the longjmp/exception
323 // runtime itself.
324
325 AllocaInst *DynamicTop = nullptr;
326 if (NeedDynamicTop)
327 // If we also have dynamic alloca's, the stack pointer value changes
328 // throughout the function. For now we store it in an alloca.
329 DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
330 "unsafe_stack_dynamic_ptr");
331
332 if (!StaticTop)
333 // We need the original unsafe stack pointer value, even if there are
334 // no unsafe static allocas.
335 StaticTop = IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
336
337 if (NeedDynamicTop)
338 IRB.CreateStore(StaticTop, DynamicTop);
339
340 // Restore current stack pointer after longjmp/exception catch.
341 for (Instruction *I : StackRestorePoints) {
342 ++NumUnsafeStackRestorePoints;
343
344 IRB.SetInsertPoint(cast<Instruction>(I->getNextNode()));
345 Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
346 IRB.CreateStore(CurrentTop, UnsafeStackPtr);
347 }
348
349 return DynamicTop;
350}
351
352Value *
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000353SafeStack::moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000354 ArrayRef<AllocaInst *> StaticAllocas,
355 ArrayRef<ReturnInst *> Returns) {
356 if (StaticAllocas.empty())
357 return nullptr;
358
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000359 DIBuilder DIB(*F.getParent());
360
361 // We explicitly compute and set the unsafe stack layout for all unsafe
362 // static alloca instructions. We save the unsafe "base pointer" in the
363 // prologue into a local variable and restore it in the epilogue.
364
365 // Load the current stack pointer (we'll also use it as a base pointer).
366 // FIXME: use a dedicated register for it ?
367 Instruction *BasePointer =
368 IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
369 assert(BasePointer->getType() == StackPtrTy);
370
371 for (ReturnInst *RI : Returns) {
372 IRB.SetInsertPoint(RI);
373 IRB.CreateStore(BasePointer, UnsafeStackPtr);
374 }
375
376 // Compute maximum alignment among static objects on the unsafe stack.
377 unsigned MaxAlignment = 0;
378 for (AllocaInst *AI : StaticAllocas) {
379 Type *Ty = AI->getAllocatedType();
380 unsigned Align =
381 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
382 if (Align > MaxAlignment)
383 MaxAlignment = Align;
384 }
385
386 if (MaxAlignment > StackAlignment) {
387 // Re-align the base pointer according to the max requested alignment.
388 assert(isPowerOf2_32(MaxAlignment));
389 IRB.SetInsertPoint(cast<Instruction>(BasePointer->getNextNode()));
390 BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
391 IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
392 ConstantInt::get(IntPtrTy, ~uint64_t(MaxAlignment - 1))),
393 StackPtrTy));
394 }
395
396 // Allocate space for every unsafe static AllocaInst on the unsafe stack.
397 int64_t StaticOffset = 0; // Current stack top.
398 for (AllocaInst *AI : StaticAllocas) {
399 IRB.SetInsertPoint(AI);
400
401 auto CArraySize = cast<ConstantInt>(AI->getArraySize());
402 Type *Ty = AI->getAllocatedType();
403
404 uint64_t Size = DL->getTypeAllocSize(Ty) * CArraySize->getZExtValue();
405 if (Size == 0)
406 Size = 1; // Don't create zero-sized stack objects.
407
408 // Ensure the object is properly aligned.
409 unsigned Align =
410 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
411
412 // Add alignment.
413 // NOTE: we ensure that BasePointer itself is aligned to >= Align.
414 StaticOffset += Size;
415 StaticOffset = RoundUpToAlignment(StaticOffset, Align);
416
417 Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
418 ConstantInt::get(Int32Ty, -StaticOffset));
419 Value *NewAI = IRB.CreateBitCast(Off, AI->getType(), AI->getName());
420 if (AI->hasName() && isa<Instruction>(NewAI))
421 cast<Instruction>(NewAI)->takeName(AI);
422
423 // Replace alloc with the new location.
Evgeniy Stepanovf6081112015-09-30 19:55:43 +0000424 replaceDbgDeclareForAlloca(AI, BasePointer, DIB, /*Deref=*/true, -StaticOffset);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000425 AI->replaceAllUsesWith(NewAI);
426 AI->eraseFromParent();
427 }
428
429 // Re-align BasePointer so that our callees would see it aligned as
430 // expected.
431 // FIXME: no need to update BasePointer in leaf functions.
432 StaticOffset = RoundUpToAlignment(StaticOffset, StackAlignment);
433
434 // Update shadow stack pointer in the function epilogue.
435 IRB.SetInsertPoint(cast<Instruction>(BasePointer->getNextNode()));
436
437 Value *StaticTop =
438 IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -StaticOffset),
439 "unsafe_stack_static_top");
440 IRB.CreateStore(StaticTop, UnsafeStackPtr);
441 return StaticTop;
442}
443
444void SafeStack::moveDynamicAllocasToUnsafeStack(
445 Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
446 ArrayRef<AllocaInst *> DynamicAllocas) {
447 DIBuilder DIB(*F.getParent());
448
449 for (AllocaInst *AI : DynamicAllocas) {
450 IRBuilder<> IRB(AI);
451
452 // Compute the new SP value (after AI).
453 Value *ArraySize = AI->getArraySize();
454 if (ArraySize->getType() != IntPtrTy)
455 ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
456
457 Type *Ty = AI->getAllocatedType();
458 uint64_t TySize = DL->getTypeAllocSize(Ty);
459 Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
460
461 Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy);
462 SP = IRB.CreateSub(SP, Size);
463
464 // Align the SP value to satisfy the AllocaInst, type and stack alignments.
465 unsigned Align = std::max(
466 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()),
467 (unsigned)StackAlignment);
468
469 assert(isPowerOf2_32(Align));
470 Value *NewTop = IRB.CreateIntToPtr(
471 IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
472 StackPtrTy);
473
474 // Save the stack pointer.
475 IRB.CreateStore(NewTop, UnsafeStackPtr);
476 if (DynamicTop)
477 IRB.CreateStore(NewTop, DynamicTop);
478
479 Value *NewAI = IRB.CreateIntToPtr(SP, AI->getType());
480 if (AI->hasName() && isa<Instruction>(NewAI))
481 NewAI->takeName(AI);
482
483 replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true);
484 AI->replaceAllUsesWith(NewAI);
485 AI->eraseFromParent();
486 }
487
488 if (!DynamicAllocas.empty()) {
489 // Now go through the instructions again, replacing stacksave/stackrestore.
490 for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
491 Instruction *I = &*(It++);
492 auto II = dyn_cast<IntrinsicInst>(I);
493 if (!II)
494 continue;
495
496 if (II->getIntrinsicID() == Intrinsic::stacksave) {
497 IRBuilder<> IRB(II);
498 Instruction *LI = IRB.CreateLoad(UnsafeStackPtr);
499 LI->takeName(II);
500 II->replaceAllUsesWith(LI);
501 II->eraseFromParent();
502 } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
503 IRBuilder<> IRB(II);
504 Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
505 SI->takeName(II);
506 assert(II->use_empty());
507 II->eraseFromParent();
508 }
509 }
510 }
511}
512
513bool SafeStack::runOnFunction(Function &F) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000514 DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
515
516 if (!F.hasFnAttribute(Attribute::SafeStack)) {
517 DEBUG(dbgs() << "[SafeStack] safestack is not requested"
518 " for this function\n");
519 return false;
520 }
521
522 if (F.isDeclaration()) {
523 DEBUG(dbgs() << "[SafeStack] function definition"
524 " is not available\n");
525 return false;
526 }
527
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000528 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
529
530 TLI = TM ? TM->getSubtargetImpl(F)->getTargetLowering() : nullptr;
531
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000532 {
533 // Make sure the regular stack protector won't run on this function
534 // (safestack attribute takes precedence).
535 AttrBuilder B;
536 B.addAttribute(Attribute::StackProtect)
537 .addAttribute(Attribute::StackProtectReq)
538 .addAttribute(Attribute::StackProtectStrong);
539 F.removeAttributes(
540 AttributeSet::FunctionIndex,
541 AttributeSet::get(F.getContext(), AttributeSet::FunctionIndex, B));
542 }
543
544 if (AA->onlyReadsMemory(&F)) {
545 // XXX: we don't protect against information leak attacks for now.
546 DEBUG(dbgs() << "[SafeStack] function only reads memory\n");
547 return false;
548 }
549
550 ++NumFunctions;
551
552 SmallVector<AllocaInst *, 16> StaticAllocas;
553 SmallVector<AllocaInst *, 4> DynamicAllocas;
554 SmallVector<ReturnInst *, 4> Returns;
555
556 // Collect all points where stack gets unwound and needs to be restored
557 // This is only necessary because the runtime (setjmp and unwind code) is
558 // not aware of the unsafe stack and won't unwind/restore it prorerly.
559 // To work around this problem without changing the runtime, we insert
560 // instrumentation to restore the unsafe stack pointer when necessary.
561 SmallVector<Instruction *, 4> StackRestorePoints;
562
563 // Find all static and dynamic alloca instructions that must be moved to the
564 // unsafe stack, all return instructions and stack restore points.
565 findInsts(F, StaticAllocas, DynamicAllocas, Returns, StackRestorePoints);
566
567 if (StaticAllocas.empty() && DynamicAllocas.empty() &&
568 StackRestorePoints.empty())
569 return false; // Nothing to do in this function.
570
571 if (!StaticAllocas.empty() || !DynamicAllocas.empty())
572 ++NumUnsafeStackFunctions; // This function has the unsafe stack.
573
574 if (!StackRestorePoints.empty())
575 ++NumUnsafeStackRestorePointsFunctions;
576
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000577 IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
Evgeniy Stepanov9addbc92015-10-15 21:26:49 +0000578 UnsafeStackPtr = getOrCreateUnsafeStackPtr(IRB, F);
Peter Collingbournede26a912015-06-22 20:26:54 +0000579
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000580 // The top of the unsafe stack after all unsafe static allocas are allocated.
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000581 Value *StaticTop = moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, Returns);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000582
583 // Safe stack object that stores the current unsafe stack top. It is updated
584 // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
585 // This is only needed if we need to restore stack pointer after longjmp
586 // or exceptions, and we have dynamic allocations.
587 // FIXME: a better alternative might be to store the unsafe stack pointer
588 // before setjmp / invoke instructions.
589 AllocaInst *DynamicTop = createStackRestorePoints(
Evgeniy Stepanov8685daf2015-09-24 01:23:51 +0000590 IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000591
592 // Handle dynamic allocas.
593 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
594 DynamicAllocas);
595
596 DEBUG(dbgs() << "[SafeStack] safestack applied\n");
597 return true;
598}
599
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000600} // anonymous namespace
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000601
602char SafeStack::ID = 0;
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000603INITIALIZE_TM_PASS_BEGIN(SafeStack, "safe-stack",
604 "Safe Stack instrumentation pass", false, false)
605INITIALIZE_TM_PASS_END(SafeStack, "safe-stack",
606 "Safe Stack instrumentation pass", false, false)
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000607
Evgeniy Stepanova2002b02015-09-23 18:07:56 +0000608FunctionPass *llvm::createSafeStackPass(const llvm::TargetMachine *TM) {
609 return new SafeStack(TM);
610}