blob: fdf96cc130a47b5cb89f0ee3c525717d74df2a1a [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"
Peter Collingbourne82437bf2015-06-15 21:07:11 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/DIBuilder.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/InstIterator.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/IntrinsicInst.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/Module.h"
33#include "llvm/Pass.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/Format.h"
37#include "llvm/Support/MathExtras.h"
38#include "llvm/Support/raw_os_ostream.h"
39#include "llvm/Transforms/Utils/Local.h"
40#include "llvm/Transforms/Utils/ModuleUtils.h"
41
42using namespace llvm;
43
44#define DEBUG_TYPE "safestack"
45
46namespace llvm {
47
48STATISTIC(NumFunctions, "Total number of functions");
49STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
50STATISTIC(NumUnsafeStackRestorePointsFunctions,
51 "Number of functions that use setjmp or exceptions");
52
53STATISTIC(NumAllocas, "Total number of allocas");
54STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
55STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
56STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
57
58} // namespace llvm
59
60namespace {
61
62/// Check whether a given alloca instruction (AI) should be put on the safe
63/// stack or not. The function analyzes all uses of AI and checks whether it is
64/// only accessed in a memory safe way (as decided statically).
65bool IsSafeStackAlloca(const AllocaInst *AI) {
66 // Go through all uses of this alloca and check whether all accesses to the
67 // allocated object are statically known to be memory safe and, hence, the
68 // object can be placed on the safe stack.
69
70 SmallPtrSet<const Value *, 16> Visited;
71 SmallVector<const Instruction *, 8> WorkList;
72 WorkList.push_back(AI);
73
74 // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
75 while (!WorkList.empty()) {
76 const Instruction *V = WorkList.pop_back_val();
77 for (const Use &UI : V->uses()) {
78 auto I = cast<const Instruction>(UI.getUser());
79 assert(V == UI.get());
80
81 switch (I->getOpcode()) {
82 case Instruction::Load:
83 // Loading from a pointer is safe.
84 break;
85 case Instruction::VAArg:
86 // "va-arg" from a pointer is safe.
87 break;
88 case Instruction::Store:
89 if (V == I->getOperand(0))
90 // Stored the pointer - conservatively assume it may be unsafe.
91 return false;
92 // Storing to the pointee is safe.
93 break;
94
95 case Instruction::GetElementPtr:
96 if (!cast<const GetElementPtrInst>(I)->hasAllConstantIndices())
97 // GEP with non-constant indices can lead to memory errors.
98 // This also applies to inbounds GEPs, as the inbounds attribute
99 // represents an assumption that the address is in bounds, rather than
100 // an assertion that it is.
101 return false;
102
103 // We assume that GEP on static alloca with constant indices is safe,
104 // otherwise a compiler would detect it and warn during compilation.
105
106 if (!isa<const ConstantInt>(AI->getArraySize()))
107 // However, if the array size itself is not constant, the access
108 // might still be unsafe at runtime.
109 return false;
110
111 /* fallthrough */
112
113 case Instruction::BitCast:
114 case Instruction::IntToPtr:
115 case Instruction::PHI:
116 case Instruction::PtrToInt:
117 case Instruction::Select:
118 // The object can be safe or not, depending on how the result of the
119 // instruction is used.
120 if (Visited.insert(I).second)
121 WorkList.push_back(cast<const Instruction>(I));
122 break;
123
124 case Instruction::Call:
125 case Instruction::Invoke: {
126 // FIXME: add support for memset and memcpy intrinsics.
127 ImmutableCallSite CS(I);
128
129 // LLVM 'nocapture' attribute is only set for arguments whose address
130 // is not stored, passed around, or used in any other non-trivial way.
131 // We assume that passing a pointer to an object as a 'nocapture'
132 // argument is safe.
133 // FIXME: a more precise solution would require an interprocedural
134 // analysis here, which would look at all uses of an argument inside
135 // the function being called.
136 ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
137 for (ImmutableCallSite::arg_iterator A = B; A != E; ++A)
138 if (A->get() == V && !CS.doesNotCapture(A - B))
139 // The parameter is not marked 'nocapture' - unsafe.
140 return false;
141 continue;
142 }
143
144 default:
145 // The object is unsafe if it is used in any other way.
146 return false;
147 }
148 }
149 }
150
151 // All uses of the alloca are safe, we can place it on the safe stack.
152 return true;
153}
154
155/// The SafeStack pass splits the stack of each function into the
156/// safe stack, which is only accessed through memory safe dereferences
157/// (as determined statically), and the unsafe stack, which contains all
158/// local variables that are accessed in unsafe ways.
159class SafeStack : public FunctionPass {
160 const DataLayout *DL;
161
162 Type *StackPtrTy;
163 Type *IntPtrTy;
164 Type *Int32Ty;
165 Type *Int8Ty;
166
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000167 Constant *UnsafeStackPtr = nullptr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000168
169 /// Unsafe stack alignment. Each stack frame must ensure that the stack is
170 /// aligned to this value. We need to re-align the unsafe stack if the
171 /// alignment of any object on the stack exceeds this value.
172 ///
173 /// 16 seems like a reasonable upper bound on the alignment of objects that we
174 /// might expect to appear on the stack on most common targets.
175 enum { StackAlignment = 16 };
176
177 /// \brief Build a constant representing a pointer to the unsafe stack
178 /// pointer.
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000179 Constant *getOrCreateUnsafeStackPtr(Module &M);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000180
181 /// \brief Find all static allocas, dynamic allocas, return instructions and
182 /// stack restore points (exception unwind blocks and setjmp calls) in the
183 /// given function and append them to the respective vectors.
184 void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
185 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
186 SmallVectorImpl<ReturnInst *> &Returns,
187 SmallVectorImpl<Instruction *> &StackRestorePoints);
188
189 /// \brief Allocate space for all static allocas in \p StaticAllocas,
190 /// replace allocas with pointers into the unsafe stack and generate code to
191 /// restore the stack pointer before all return instructions in \p Returns.
192 ///
193 /// \returns A pointer to the top of the unsafe stack after all unsafe static
194 /// allocas are allocated.
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000195 Value *moveStaticAllocasToUnsafeStack(Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000196 ArrayRef<AllocaInst *> StaticAllocas,
197 ArrayRef<ReturnInst *> Returns);
198
199 /// \brief Generate code to restore the stack after all stack restore points
200 /// in \p StackRestorePoints.
201 ///
202 /// \returns A local variable in which to maintain the dynamic top of the
203 /// unsafe stack if needed.
204 AllocaInst *
205 createStackRestorePoints(Function &F,
206 ArrayRef<Instruction *> StackRestorePoints,
207 Value *StaticTop, bool NeedDynamicTop);
208
209 /// \brief Replace all allocas in \p DynamicAllocas with code to allocate
210 /// space dynamically on the unsafe stack and store the dynamic unsafe stack
211 /// top to \p DynamicTop if non-null.
212 void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
213 AllocaInst *DynamicTop,
214 ArrayRef<AllocaInst *> DynamicAllocas);
215
216public:
217 static char ID; // Pass identification, replacement for typeid.
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000218 SafeStack() : FunctionPass(ID), DL(nullptr) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000219 initializeSafeStackPass(*PassRegistry::getPassRegistry());
220 }
221
Hans Wennborgaa15bff2015-09-10 16:49:58 +0000222 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000223 AU.addRequired<AAResultsWrapperPass>();
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000224 }
225
Hans Wennborgaa15bff2015-09-10 16:49:58 +0000226 bool doInitialization(Module &M) override {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000227 DL = &M.getDataLayout();
228
229 StackPtrTy = Type::getInt8PtrTy(M.getContext());
230 IntPtrTy = DL->getIntPtrType(M.getContext());
231 Int32Ty = Type::getInt32Ty(M.getContext());
232 Int8Ty = Type::getInt8Ty(M.getContext());
233
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000234 return false;
235 }
236
Hans Wennborgaa15bff2015-09-10 16:49:58 +0000237 bool runOnFunction(Function &F) override;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000238}; // class SafeStack
239
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000240Constant *SafeStack::getOrCreateUnsafeStackPtr(Module &M) {
241 // The unsafe stack pointer is stored in a global variable with a magic name.
242 const char *kUnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000243
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000244 auto UnsafeStackPtr =
245 dyn_cast_or_null<GlobalVariable>(M.getNamedValue(kUnsafeStackPtrVar));
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000246
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000247 if (!UnsafeStackPtr) {
248 // The global variable is not defined yet, define it ourselves.
249 // We use the initial-exec TLS model because we do not support the variable
250 // living anywhere other than in the main executable.
251 UnsafeStackPtr = new GlobalVariable(
252 /*Module=*/M, /*Type=*/StackPtrTy,
253 /*isConstant=*/false, /*Linkage=*/GlobalValue::ExternalLinkage,
254 /*Initializer=*/0, /*Name=*/kUnsafeStackPtrVar,
255 /*InsertBefore=*/nullptr,
256 /*ThreadLocalMode=*/GlobalValue::InitialExecTLSModel);
Evgeniy Stepanovce2e16f2015-09-23 01:03:51 +0000257 } else {
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000258 // The variable exists, check its type and attributes.
259 if (UnsafeStackPtr->getValueType() != StackPtrTy) {
260 report_fatal_error(Twine(kUnsafeStackPtrVar) + " must have void* type");
Evgeniy Stepanovce2e16f2015-09-23 01:03:51 +0000261 }
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000262
263 if (!UnsafeStackPtr->isThreadLocal()) {
264 report_fatal_error(Twine(kUnsafeStackPtrVar) + " must be thread-local");
265 }
Evgeniy Stepanovce2e16f2015-09-23 01:03:51 +0000266 }
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000267
268 return UnsafeStackPtr;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000269}
270
271void SafeStack::findInsts(Function &F,
272 SmallVectorImpl<AllocaInst *> &StaticAllocas,
273 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
274 SmallVectorImpl<ReturnInst *> &Returns,
275 SmallVectorImpl<Instruction *> &StackRestorePoints) {
Nico Rieck78199512015-08-06 19:10:45 +0000276 for (Instruction &I : instructions(&F)) {
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000277 if (auto AI = dyn_cast<AllocaInst>(&I)) {
278 ++NumAllocas;
279
280 if (IsSafeStackAlloca(AI))
281 continue;
282
283 if (AI->isStaticAlloca()) {
284 ++NumUnsafeStaticAllocas;
285 StaticAllocas.push_back(AI);
286 } else {
287 ++NumUnsafeDynamicAllocas;
288 DynamicAllocas.push_back(AI);
289 }
290 } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
291 Returns.push_back(RI);
292 } else if (auto CI = dyn_cast<CallInst>(&I)) {
293 // setjmps require stack restore.
294 if (CI->getCalledFunction() && CI->canReturnTwice())
295 StackRestorePoints.push_back(CI);
296 } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
297 // Exception landing pads require stack restore.
298 StackRestorePoints.push_back(LP);
299 } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
300 if (II->getIntrinsicID() == Intrinsic::gcroot)
301 llvm::report_fatal_error(
302 "gcroot intrinsic not compatible with safestack attribute");
303 }
304 }
305}
306
307AllocaInst *
308SafeStack::createStackRestorePoints(Function &F,
309 ArrayRef<Instruction *> StackRestorePoints,
310 Value *StaticTop, bool NeedDynamicTop) {
311 if (StackRestorePoints.empty())
312 return nullptr;
313
314 IRBuilder<> IRB(StaticTop
315 ? cast<Instruction>(StaticTop)->getNextNode()
316 : (Instruction *)F.getEntryBlock().getFirstInsertionPt());
317
318 // We need the current value of the shadow stack pointer to restore
319 // after longjmp or exception catching.
320
321 // FIXME: On some platforms this could be handled by the longjmp/exception
322 // runtime itself.
323
324 AllocaInst *DynamicTop = nullptr;
325 if (NeedDynamicTop)
326 // If we also have dynamic alloca's, the stack pointer value changes
327 // throughout the function. For now we store it in an alloca.
328 DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
329 "unsafe_stack_dynamic_ptr");
330
331 if (!StaticTop)
332 // We need the original unsafe stack pointer value, even if there are
333 // no unsafe static allocas.
334 StaticTop = IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
335
336 if (NeedDynamicTop)
337 IRB.CreateStore(StaticTop, DynamicTop);
338
339 // Restore current stack pointer after longjmp/exception catch.
340 for (Instruction *I : StackRestorePoints) {
341 ++NumUnsafeStackRestorePoints;
342
343 IRB.SetInsertPoint(cast<Instruction>(I->getNextNode()));
344 Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
345 IRB.CreateStore(CurrentTop, UnsafeStackPtr);
346 }
347
348 return DynamicTop;
349}
350
351Value *
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000352SafeStack::moveStaticAllocasToUnsafeStack(Function &F,
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000353 ArrayRef<AllocaInst *> StaticAllocas,
354 ArrayRef<ReturnInst *> Returns) {
355 if (StaticAllocas.empty())
356 return nullptr;
357
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000358 IRBuilder<> IRB(F.getEntryBlock().getFirstInsertionPt());
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.
424 replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true);
425 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) {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000514 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000515
516 DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
517
518 if (!F.hasFnAttribute(Attribute::SafeStack)) {
519 DEBUG(dbgs() << "[SafeStack] safestack is not requested"
520 " for this function\n");
521 return false;
522 }
523
524 if (F.isDeclaration()) {
525 DEBUG(dbgs() << "[SafeStack] function definition"
526 " is not available\n");
527 return false;
528 }
529
530 {
531 // Make sure the regular stack protector won't run on this function
532 // (safestack attribute takes precedence).
533 AttrBuilder B;
534 B.addAttribute(Attribute::StackProtect)
535 .addAttribute(Attribute::StackProtectReq)
536 .addAttribute(Attribute::StackProtectStrong);
537 F.removeAttributes(
538 AttributeSet::FunctionIndex,
539 AttributeSet::get(F.getContext(), AttributeSet::FunctionIndex, B));
540 }
541
542 if (AA->onlyReadsMemory(&F)) {
543 // XXX: we don't protect against information leak attacks for now.
544 DEBUG(dbgs() << "[SafeStack] function only reads memory\n");
545 return false;
546 }
547
548 ++NumFunctions;
549
550 SmallVector<AllocaInst *, 16> StaticAllocas;
551 SmallVector<AllocaInst *, 4> DynamicAllocas;
552 SmallVector<ReturnInst *, 4> Returns;
553
554 // Collect all points where stack gets unwound and needs to be restored
555 // This is only necessary because the runtime (setjmp and unwind code) is
556 // not aware of the unsafe stack and won't unwind/restore it prorerly.
557 // To work around this problem without changing the runtime, we insert
558 // instrumentation to restore the unsafe stack pointer when necessary.
559 SmallVector<Instruction *, 4> StackRestorePoints;
560
561 // Find all static and dynamic alloca instructions that must be moved to the
562 // unsafe stack, all return instructions and stack restore points.
563 findInsts(F, StaticAllocas, DynamicAllocas, Returns, StackRestorePoints);
564
565 if (StaticAllocas.empty() && DynamicAllocas.empty() &&
566 StackRestorePoints.empty())
567 return false; // Nothing to do in this function.
568
569 if (!StaticAllocas.empty() || !DynamicAllocas.empty())
570 ++NumUnsafeStackFunctions; // This function has the unsafe stack.
571
572 if (!StackRestorePoints.empty())
573 ++NumUnsafeStackRestorePointsFunctions;
574
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000575 if (!UnsafeStackPtr)
576 UnsafeStackPtr = getOrCreateUnsafeStackPtr(*F.getParent());
Peter Collingbournede26a912015-06-22 20:26:54 +0000577
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000578 // The top of the unsafe stack after all unsafe static allocas are allocated.
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000579 Value *StaticTop = moveStaticAllocasToUnsafeStack(F, StaticAllocas, Returns);
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000580
581 // Safe stack object that stores the current unsafe stack top. It is updated
582 // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
583 // This is only needed if we need to restore stack pointer after longjmp
584 // or exceptions, and we have dynamic allocations.
585 // FIXME: a better alternative might be to store the unsafe stack pointer
586 // before setjmp / invoke instructions.
587 AllocaInst *DynamicTop = createStackRestorePoints(
588 F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
589
590 // Handle dynamic allocas.
591 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
592 DynamicAllocas);
593
594 DEBUG(dbgs() << "[SafeStack] safestack applied\n");
595 return true;
596}
597
598} // end anonymous namespace
599
600char SafeStack::ID = 0;
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000601INITIALIZE_PASS_BEGIN(SafeStack, "safe-stack",
602 "Safe Stack instrumentation pass", false, false)
603INITIALIZE_PASS_END(SafeStack, "safe-stack", "Safe Stack instrumentation pass",
604 false, false)
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000605
Evgeniy Stepanov8d0e3012015-09-23 01:23:22 +0000606FunctionPass *llvm::createSafeStackPass() { return new SafeStack(); }