1 //===-- SafeStack.cpp - Safe Stack Insertion ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 // http://clang.llvm.org/docs/SafeStack.html
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Instrumentation.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/Passes.h"
23 #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"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include "llvm/Transforms/Utils/ModuleUtils.h"
47 #define DEBUG_TYPE "safestack"
51 STATISTIC(NumFunctions, "Total number of functions");
52 STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
53 STATISTIC(NumUnsafeStackRestorePointsFunctions,
54 "Number of functions that use setjmp or exceptions");
56 STATISTIC(NumAllocas, "Total number of allocas");
57 STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
58 STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
59 STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
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).
68 bool 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.
73 SmallPtrSet<const Value *, 16> Visited;
74 SmallVector<const Instruction *, 8> WorkList;
75 WorkList.push_back(AI);
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());
84 switch (I->getOpcode()) {
85 case Instruction::Load:
86 // Loading from a pointer is safe.
88 case Instruction::VAArg:
89 // "va-arg" from a pointer is safe.
91 case Instruction::Store:
92 if (V == I->getOperand(0))
93 // Stored the pointer - conservatively assume it may be unsafe.
95 // Storing to the pointee is safe.
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.
106 // We assume that GEP on static alloca with constant indices is safe,
107 // otherwise a compiler would detect it and warn during compilation.
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.
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));
127 case Instruction::Call:
128 case Instruction::Invoke: {
129 // FIXME: add support for memset and memcpy intrinsics.
130 ImmutableCallSite CS(I);
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'
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.
148 // The object is unsafe if it is used in any other way.
154 // All uses of the alloca are safe, we can place it on the safe stack.
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.
162 class SafeStack : public FunctionPass {
163 const TargetMachine *TM;
164 const TargetLoweringBase *TLI;
165 const DataLayout *DL;
172 Value *UnsafeStackPtr = nullptr;
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.
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 };
182 /// \brief Find all static allocas, dynamic allocas, return instructions and
183 /// stack restore points (exception unwind blocks and setjmp calls) in the
184 /// given function and append them to the respective vectors.
185 void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
186 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
187 SmallVectorImpl<ReturnInst *> &Returns,
188 SmallVectorImpl<Instruction *> &StackRestorePoints);
190 /// \brief Allocate space for all static allocas in \p StaticAllocas,
191 /// replace allocas with pointers into the unsafe stack and generate code to
192 /// restore the stack pointer before all return instructions in \p Returns.
194 /// \returns A pointer to the top of the unsafe stack after all unsafe static
195 /// allocas are allocated.
196 Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
197 ArrayRef<AllocaInst *> StaticAllocas,
198 ArrayRef<ReturnInst *> Returns);
200 /// \brief Generate code to restore the stack after all stack restore points
201 /// in \p StackRestorePoints.
203 /// \returns A local variable in which to maintain the dynamic top of the
204 /// unsafe stack if needed.
206 createStackRestorePoints(IRBuilder<> &IRB, Function &F,
207 ArrayRef<Instruction *> StackRestorePoints,
208 Value *StaticTop, bool NeedDynamicTop);
210 /// \brief Replace all allocas in \p DynamicAllocas with code to allocate
211 /// space dynamically on the unsafe stack and store the dynamic unsafe stack
212 /// top to \p DynamicTop if non-null.
213 void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
214 AllocaInst *DynamicTop,
215 ArrayRef<AllocaInst *> DynamicAllocas);
218 static char ID; // Pass identification, replacement for typeid.
219 SafeStack(const TargetMachine *TM)
220 : FunctionPass(ID), TM(TM), TLI(nullptr), DL(nullptr) {
221 initializeSafeStackPass(*PassRegistry::getPassRegistry());
223 SafeStack() : SafeStack(nullptr) {}
225 void getAnalysisUsage(AnalysisUsage &AU) const override {
226 AU.addRequired<AAResultsWrapperPass>();
229 bool doInitialization(Module &M) override {
230 DL = &M.getDataLayout();
232 StackPtrTy = Type::getInt8PtrTy(M.getContext());
233 IntPtrTy = DL->getIntPtrType(M.getContext());
234 Int32Ty = Type::getInt32Ty(M.getContext());
235 Int8Ty = Type::getInt8Ty(M.getContext());
240 bool runOnFunction(Function &F) override;
241 }; // class SafeStack
243 void SafeStack::findInsts(Function &F,
244 SmallVectorImpl<AllocaInst *> &StaticAllocas,
245 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
246 SmallVectorImpl<ReturnInst *> &Returns,
247 SmallVectorImpl<Instruction *> &StackRestorePoints) {
248 for (Instruction &I : instructions(&F)) {
249 if (auto AI = dyn_cast<AllocaInst>(&I)) {
252 if (IsSafeStackAlloca(AI))
255 if (AI->isStaticAlloca()) {
256 ++NumUnsafeStaticAllocas;
257 StaticAllocas.push_back(AI);
259 ++NumUnsafeDynamicAllocas;
260 DynamicAllocas.push_back(AI);
262 } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
263 Returns.push_back(RI);
264 } else if (auto CI = dyn_cast<CallInst>(&I)) {
265 // setjmps require stack restore.
266 if (CI->getCalledFunction() && CI->canReturnTwice())
267 StackRestorePoints.push_back(CI);
268 } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
269 // Exception landing pads require stack restore.
270 StackRestorePoints.push_back(LP);
271 } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
272 if (II->getIntrinsicID() == Intrinsic::gcroot)
273 llvm::report_fatal_error(
274 "gcroot intrinsic not compatible with safestack attribute");
280 SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
281 ArrayRef<Instruction *> StackRestorePoints,
282 Value *StaticTop, bool NeedDynamicTop) {
283 if (StackRestorePoints.empty())
286 // We need the current value of the shadow stack pointer to restore
287 // after longjmp or exception catching.
289 // FIXME: On some platforms this could be handled by the longjmp/exception
292 AllocaInst *DynamicTop = nullptr;
294 // If we also have dynamic alloca's, the stack pointer value changes
295 // throughout the function. For now we store it in an alloca.
296 DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
297 "unsafe_stack_dynamic_ptr");
300 // We need the original unsafe stack pointer value, even if there are
301 // no unsafe static allocas.
302 StaticTop = IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
305 IRB.CreateStore(StaticTop, DynamicTop);
307 // Restore current stack pointer after longjmp/exception catch.
308 for (Instruction *I : StackRestorePoints) {
309 ++NumUnsafeStackRestorePoints;
311 IRB.SetInsertPoint(cast<Instruction>(I->getNextNode()));
312 Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
313 IRB.CreateStore(CurrentTop, UnsafeStackPtr);
320 SafeStack::moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
321 ArrayRef<AllocaInst *> StaticAllocas,
322 ArrayRef<ReturnInst *> Returns) {
323 if (StaticAllocas.empty())
326 DIBuilder DIB(*F.getParent());
328 // We explicitly compute and set the unsafe stack layout for all unsafe
329 // static alloca instructions. We save the unsafe "base pointer" in the
330 // prologue into a local variable and restore it in the epilogue.
332 // Load the current stack pointer (we'll also use it as a base pointer).
333 // FIXME: use a dedicated register for it ?
334 Instruction *BasePointer =
335 IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
336 assert(BasePointer->getType() == StackPtrTy);
338 for (ReturnInst *RI : Returns) {
339 IRB.SetInsertPoint(RI);
340 IRB.CreateStore(BasePointer, UnsafeStackPtr);
343 // Compute maximum alignment among static objects on the unsafe stack.
344 unsigned MaxAlignment = 0;
345 for (AllocaInst *AI : StaticAllocas) {
346 Type *Ty = AI->getAllocatedType();
348 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
349 if (Align > MaxAlignment)
350 MaxAlignment = Align;
353 if (MaxAlignment > StackAlignment) {
354 // Re-align the base pointer according to the max requested alignment.
355 assert(isPowerOf2_32(MaxAlignment));
356 IRB.SetInsertPoint(cast<Instruction>(BasePointer->getNextNode()));
357 BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
358 IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
359 ConstantInt::get(IntPtrTy, ~uint64_t(MaxAlignment - 1))),
363 // Allocate space for every unsafe static AllocaInst on the unsafe stack.
364 int64_t StaticOffset = 0; // Current stack top.
365 for (AllocaInst *AI : StaticAllocas) {
366 IRB.SetInsertPoint(AI);
368 auto CArraySize = cast<ConstantInt>(AI->getArraySize());
369 Type *Ty = AI->getAllocatedType();
371 uint64_t Size = DL->getTypeAllocSize(Ty) * CArraySize->getZExtValue();
373 Size = 1; // Don't create zero-sized stack objects.
375 // Ensure the object is properly aligned.
377 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
380 // NOTE: we ensure that BasePointer itself is aligned to >= Align.
381 StaticOffset += Size;
382 StaticOffset = RoundUpToAlignment(StaticOffset, Align);
384 Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
385 ConstantInt::get(Int32Ty, -StaticOffset));
386 Value *NewAI = IRB.CreateBitCast(Off, AI->getType(), AI->getName());
387 if (AI->hasName() && isa<Instruction>(NewAI))
388 cast<Instruction>(NewAI)->takeName(AI);
390 // Replace alloc with the new location.
391 replaceDbgDeclareForAlloca(AI, BasePointer, DIB, /*Deref=*/true, -StaticOffset);
392 AI->replaceAllUsesWith(NewAI);
393 AI->eraseFromParent();
396 // Re-align BasePointer so that our callees would see it aligned as
398 // FIXME: no need to update BasePointer in leaf functions.
399 StaticOffset = RoundUpToAlignment(StaticOffset, StackAlignment);
401 // Update shadow stack pointer in the function epilogue.
402 IRB.SetInsertPoint(cast<Instruction>(BasePointer->getNextNode()));
405 IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -StaticOffset),
406 "unsafe_stack_static_top");
407 IRB.CreateStore(StaticTop, UnsafeStackPtr);
411 void SafeStack::moveDynamicAllocasToUnsafeStack(
412 Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
413 ArrayRef<AllocaInst *> DynamicAllocas) {
414 DIBuilder DIB(*F.getParent());
416 for (AllocaInst *AI : DynamicAllocas) {
419 // Compute the new SP value (after AI).
420 Value *ArraySize = AI->getArraySize();
421 if (ArraySize->getType() != IntPtrTy)
422 ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
424 Type *Ty = AI->getAllocatedType();
425 uint64_t TySize = DL->getTypeAllocSize(Ty);
426 Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
428 Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy);
429 SP = IRB.CreateSub(SP, Size);
431 // Align the SP value to satisfy the AllocaInst, type and stack alignments.
432 unsigned Align = std::max(
433 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()),
434 (unsigned)StackAlignment);
436 assert(isPowerOf2_32(Align));
437 Value *NewTop = IRB.CreateIntToPtr(
438 IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
441 // Save the stack pointer.
442 IRB.CreateStore(NewTop, UnsafeStackPtr);
444 IRB.CreateStore(NewTop, DynamicTop);
446 Value *NewAI = IRB.CreateIntToPtr(SP, AI->getType());
447 if (AI->hasName() && isa<Instruction>(NewAI))
450 replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true);
451 AI->replaceAllUsesWith(NewAI);
452 AI->eraseFromParent();
455 if (!DynamicAllocas.empty()) {
456 // Now go through the instructions again, replacing stacksave/stackrestore.
457 for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
458 Instruction *I = &*(It++);
459 auto II = dyn_cast<IntrinsicInst>(I);
463 if (II->getIntrinsicID() == Intrinsic::stacksave) {
465 Instruction *LI = IRB.CreateLoad(UnsafeStackPtr);
467 II->replaceAllUsesWith(LI);
468 II->eraseFromParent();
469 } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
471 Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
473 assert(II->use_empty());
474 II->eraseFromParent();
480 bool SafeStack::runOnFunction(Function &F) {
481 DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
483 if (!F.hasFnAttribute(Attribute::SafeStack)) {
484 DEBUG(dbgs() << "[SafeStack] safestack is not requested"
485 " for this function\n");
489 if (F.isDeclaration()) {
490 DEBUG(dbgs() << "[SafeStack] function definition"
491 " is not available\n");
495 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
497 TLI = TM ? TM->getSubtargetImpl(F)->getTargetLowering() : nullptr;
500 // Make sure the regular stack protector won't run on this function
501 // (safestack attribute takes precedence).
503 B.addAttribute(Attribute::StackProtect)
504 .addAttribute(Attribute::StackProtectReq)
505 .addAttribute(Attribute::StackProtectStrong);
507 AttributeSet::FunctionIndex,
508 AttributeSet::get(F.getContext(), AttributeSet::FunctionIndex, B));
511 if (AA->onlyReadsMemory(&F)) {
512 // XXX: we don't protect against information leak attacks for now.
513 DEBUG(dbgs() << "[SafeStack] function only reads memory\n");
519 SmallVector<AllocaInst *, 16> StaticAllocas;
520 SmallVector<AllocaInst *, 4> DynamicAllocas;
521 SmallVector<ReturnInst *, 4> Returns;
523 // Collect all points where stack gets unwound and needs to be restored
524 // This is only necessary because the runtime (setjmp and unwind code) is
525 // not aware of the unsafe stack and won't unwind/restore it prorerly.
526 // To work around this problem without changing the runtime, we insert
527 // instrumentation to restore the unsafe stack pointer when necessary.
528 SmallVector<Instruction *, 4> StackRestorePoints;
530 // Find all static and dynamic alloca instructions that must be moved to the
531 // unsafe stack, all return instructions and stack restore points.
532 findInsts(F, StaticAllocas, DynamicAllocas, Returns, StackRestorePoints);
534 if (StaticAllocas.empty() && DynamicAllocas.empty() &&
535 StackRestorePoints.empty())
536 return false; // Nothing to do in this function.
538 if (!StaticAllocas.empty() || !DynamicAllocas.empty())
539 ++NumUnsafeStackFunctions; // This function has the unsafe stack.
541 if (!StackRestorePoints.empty())
542 ++NumUnsafeStackRestorePointsFunctions;
544 IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
545 UnsafeStackPtr = TLI->getSafeStackPointerLocation(IRB);
547 // The top of the unsafe stack after all unsafe static allocas are allocated.
548 Value *StaticTop = moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, Returns);
550 // Safe stack object that stores the current unsafe stack top. It is updated
551 // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
552 // This is only needed if we need to restore stack pointer after longjmp
553 // or exceptions, and we have dynamic allocations.
554 // FIXME: a better alternative might be to store the unsafe stack pointer
555 // before setjmp / invoke instructions.
556 AllocaInst *DynamicTop = createStackRestorePoints(
557 IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
559 // Handle dynamic allocas.
560 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
563 DEBUG(dbgs() << "[SafeStack] safestack applied\n");
567 } // anonymous namespace
569 char SafeStack::ID = 0;
570 INITIALIZE_TM_PASS_BEGIN(SafeStack, "safe-stack",
571 "Safe Stack instrumentation pass", false, false)
572 INITIALIZE_TM_PASS_END(SafeStack, "safe-stack",
573 "Safe Stack instrumentation pass", false, false)
575 FunctionPass *llvm::createSafeStackPass(const llvm::TargetMachine *TM) {
576 return new SafeStack(TM);