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/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"
44 #define DEBUG_TYPE "safestack"
48 STATISTIC(NumFunctions, "Total number of functions");
49 STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
50 STATISTIC(NumUnsafeStackRestorePointsFunctions,
51 "Number of functions that use setjmp or exceptions");
53 STATISTIC(NumAllocas, "Total number of allocas");
54 STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
55 STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
56 STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
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).
65 bool 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.
70 SmallPtrSet<const Value *, 16> Visited;
71 SmallVector<const Instruction *, 8> WorkList;
72 WorkList.push_back(AI);
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());
81 switch (I->getOpcode()) {
82 case Instruction::Load:
83 // Loading from a pointer is safe.
85 case Instruction::VAArg:
86 // "va-arg" from a pointer is safe.
88 case Instruction::Store:
89 if (V == I->getOperand(0))
90 // Stored the pointer - conservatively assume it may be unsafe.
92 // Storing to the pointee is safe.
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.
103 // We assume that GEP on static alloca with constant indices is safe,
104 // otherwise a compiler would detect it and warn during compilation.
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.
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));
124 case Instruction::Call:
125 case Instruction::Invoke: {
126 // FIXME: add support for memset and memcpy intrinsics.
127 ImmutableCallSite CS(I);
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'
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.
145 // The object is unsafe if it is used in any other way.
151 // All uses of the alloca are safe, we can place it on the safe stack.
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.
159 class SafeStack : public FunctionPass {
160 const DataLayout *DL;
167 Constant *UnsafeStackPtr = nullptr;
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.
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 };
177 /// \brief Build a constant representing a pointer to the unsafe stack
179 Constant *getOrCreateUnsafeStackPtr(Module &M);
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);
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.
193 /// \returns A pointer to the top of the unsafe stack after all unsafe static
194 /// allocas are allocated.
195 Value *moveStaticAllocasToUnsafeStack(Function &F,
196 ArrayRef<AllocaInst *> StaticAllocas,
197 ArrayRef<ReturnInst *> Returns);
199 /// \brief Generate code to restore the stack after all stack restore points
200 /// in \p StackRestorePoints.
202 /// \returns A local variable in which to maintain the dynamic top of the
203 /// unsafe stack if needed.
205 createStackRestorePoints(Function &F,
206 ArrayRef<Instruction *> StackRestorePoints,
207 Value *StaticTop, bool NeedDynamicTop);
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);
217 static char ID; // Pass identification, replacement for typeid.
218 SafeStack() : FunctionPass(ID), DL(nullptr) {
219 initializeSafeStackPass(*PassRegistry::getPassRegistry());
222 void getAnalysisUsage(AnalysisUsage &AU) const override {
223 AU.addRequired<AAResultsWrapperPass>();
226 bool doInitialization(Module &M) override {
227 DL = &M.getDataLayout();
229 StackPtrTy = Type::getInt8PtrTy(M.getContext());
230 IntPtrTy = DL->getIntPtrType(M.getContext());
231 Int32Ty = Type::getInt32Ty(M.getContext());
232 Int8Ty = Type::getInt8Ty(M.getContext());
237 bool runOnFunction(Function &F) override;
238 }; // class SafeStack
240 Constant *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";
244 auto UnsafeStackPtr =
245 dyn_cast_or_null<GlobalVariable>(M.getNamedValue(kUnsafeStackPtrVar));
247 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);
258 // The variable exists, check its type and attributes.
259 if (UnsafeStackPtr->getValueType() != StackPtrTy) {
260 report_fatal_error(Twine(kUnsafeStackPtrVar) + " must have void* type");
263 if (!UnsafeStackPtr->isThreadLocal()) {
264 report_fatal_error(Twine(kUnsafeStackPtrVar) + " must be thread-local");
268 return UnsafeStackPtr;
271 void SafeStack::findInsts(Function &F,
272 SmallVectorImpl<AllocaInst *> &StaticAllocas,
273 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
274 SmallVectorImpl<ReturnInst *> &Returns,
275 SmallVectorImpl<Instruction *> &StackRestorePoints) {
276 for (Instruction &I : instructions(&F)) {
277 if (auto AI = dyn_cast<AllocaInst>(&I)) {
280 if (IsSafeStackAlloca(AI))
283 if (AI->isStaticAlloca()) {
284 ++NumUnsafeStaticAllocas;
285 StaticAllocas.push_back(AI);
287 ++NumUnsafeDynamicAllocas;
288 DynamicAllocas.push_back(AI);
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");
308 SafeStack::createStackRestorePoints(Function &F,
309 ArrayRef<Instruction *> StackRestorePoints,
310 Value *StaticTop, bool NeedDynamicTop) {
311 if (StackRestorePoints.empty())
314 IRBuilder<> IRB(StaticTop
315 ? cast<Instruction>(StaticTop)->getNextNode()
316 : (Instruction *)F.getEntryBlock().getFirstInsertionPt());
318 // We need the current value of the shadow stack pointer to restore
319 // after longjmp or exception catching.
321 // FIXME: On some platforms this could be handled by the longjmp/exception
324 AllocaInst *DynamicTop = nullptr;
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");
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");
337 IRB.CreateStore(StaticTop, DynamicTop);
339 // Restore current stack pointer after longjmp/exception catch.
340 for (Instruction *I : StackRestorePoints) {
341 ++NumUnsafeStackRestorePoints;
343 IRB.SetInsertPoint(cast<Instruction>(I->getNextNode()));
344 Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
345 IRB.CreateStore(CurrentTop, UnsafeStackPtr);
352 SafeStack::moveStaticAllocasToUnsafeStack(Function &F,
353 ArrayRef<AllocaInst *> StaticAllocas,
354 ArrayRef<ReturnInst *> Returns) {
355 if (StaticAllocas.empty())
358 IRBuilder<> IRB(F.getEntryBlock().getFirstInsertionPt());
359 DIBuilder DIB(*F.getParent());
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.
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);
371 for (ReturnInst *RI : Returns) {
372 IRB.SetInsertPoint(RI);
373 IRB.CreateStore(BasePointer, UnsafeStackPtr);
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();
381 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
382 if (Align > MaxAlignment)
383 MaxAlignment = Align;
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))),
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);
401 auto CArraySize = cast<ConstantInt>(AI->getArraySize());
402 Type *Ty = AI->getAllocatedType();
404 uint64_t Size = DL->getTypeAllocSize(Ty) * CArraySize->getZExtValue();
406 Size = 1; // Don't create zero-sized stack objects.
408 // Ensure the object is properly aligned.
410 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
413 // NOTE: we ensure that BasePointer itself is aligned to >= Align.
414 StaticOffset += Size;
415 StaticOffset = RoundUpToAlignment(StaticOffset, Align);
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);
423 // Replace alloc with the new location.
424 replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true);
425 AI->replaceAllUsesWith(NewAI);
426 AI->eraseFromParent();
429 // Re-align BasePointer so that our callees would see it aligned as
431 // FIXME: no need to update BasePointer in leaf functions.
432 StaticOffset = RoundUpToAlignment(StaticOffset, StackAlignment);
434 // Update shadow stack pointer in the function epilogue.
435 IRB.SetInsertPoint(cast<Instruction>(BasePointer->getNextNode()));
438 IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -StaticOffset),
439 "unsafe_stack_static_top");
440 IRB.CreateStore(StaticTop, UnsafeStackPtr);
444 void SafeStack::moveDynamicAllocasToUnsafeStack(
445 Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
446 ArrayRef<AllocaInst *> DynamicAllocas) {
447 DIBuilder DIB(*F.getParent());
449 for (AllocaInst *AI : DynamicAllocas) {
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);
457 Type *Ty = AI->getAllocatedType();
458 uint64_t TySize = DL->getTypeAllocSize(Ty);
459 Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
461 Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy);
462 SP = IRB.CreateSub(SP, Size);
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);
469 assert(isPowerOf2_32(Align));
470 Value *NewTop = IRB.CreateIntToPtr(
471 IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
474 // Save the stack pointer.
475 IRB.CreateStore(NewTop, UnsafeStackPtr);
477 IRB.CreateStore(NewTop, DynamicTop);
479 Value *NewAI = IRB.CreateIntToPtr(SP, AI->getType());
480 if (AI->hasName() && isa<Instruction>(NewAI))
483 replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true);
484 AI->replaceAllUsesWith(NewAI);
485 AI->eraseFromParent();
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);
496 if (II->getIntrinsicID() == Intrinsic::stacksave) {
498 Instruction *LI = IRB.CreateLoad(UnsafeStackPtr);
500 II->replaceAllUsesWith(LI);
501 II->eraseFromParent();
502 } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
504 Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
506 assert(II->use_empty());
507 II->eraseFromParent();
513 bool SafeStack::runOnFunction(Function &F) {
514 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
516 DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
518 if (!F.hasFnAttribute(Attribute::SafeStack)) {
519 DEBUG(dbgs() << "[SafeStack] safestack is not requested"
520 " for this function\n");
524 if (F.isDeclaration()) {
525 DEBUG(dbgs() << "[SafeStack] function definition"
526 " is not available\n");
531 // Make sure the regular stack protector won't run on this function
532 // (safestack attribute takes precedence).
534 B.addAttribute(Attribute::StackProtect)
535 .addAttribute(Attribute::StackProtectReq)
536 .addAttribute(Attribute::StackProtectStrong);
538 AttributeSet::FunctionIndex,
539 AttributeSet::get(F.getContext(), AttributeSet::FunctionIndex, B));
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");
550 SmallVector<AllocaInst *, 16> StaticAllocas;
551 SmallVector<AllocaInst *, 4> DynamicAllocas;
552 SmallVector<ReturnInst *, 4> Returns;
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;
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);
565 if (StaticAllocas.empty() && DynamicAllocas.empty() &&
566 StackRestorePoints.empty())
567 return false; // Nothing to do in this function.
569 if (!StaticAllocas.empty() || !DynamicAllocas.empty())
570 ++NumUnsafeStackFunctions; // This function has the unsafe stack.
572 if (!StackRestorePoints.empty())
573 ++NumUnsafeStackRestorePointsFunctions;
576 UnsafeStackPtr = getOrCreateUnsafeStackPtr(*F.getParent());
578 // The top of the unsafe stack after all unsafe static allocas are allocated.
579 Value *StaticTop = moveStaticAllocasToUnsafeStack(F, StaticAllocas, Returns);
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());
590 // Handle dynamic allocas.
591 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
594 DEBUG(dbgs() << "[SafeStack] safestack applied\n");
598 } // end anonymous namespace
600 char SafeStack::ID = 0;
601 INITIALIZE_PASS_BEGIN(SafeStack, "safe-stack",
602 "Safe Stack instrumentation pass", false, false)
603 INITIALIZE_PASS_END(SafeStack, "safe-stack", "Safe Stack instrumentation pass",
606 FunctionPass *llvm::createSafeStackPass() { return new SafeStack(); }