1 //===- SafeStack.cpp - Safe Stack Insertion -------------------------------===//
3 // 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
7 //===----------------------------------------------------------------------===//
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
13 // http://clang.llvm.org/docs/SafeStack.html
15 //===----------------------------------------------------------------------===//
17 #include "SafeStackLayout.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AssumptionCache.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/Analysis/DomTreeUpdater.h"
26 #include "llvm/Analysis/InlineCost.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
30 #include "llvm/Analysis/StackLifetime.h"
31 #include "llvm/Analysis/TargetLibraryInfo.h"
32 #include "llvm/CodeGen/TargetLowering.h"
33 #include "llvm/CodeGen/TargetPassConfig.h"
34 #include "llvm/CodeGen/TargetSubtargetInfo.h"
35 #include "llvm/IR/Argument.h"
36 #include "llvm/IR/Attributes.h"
37 #include "llvm/IR/ConstantRange.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DIBuilder.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Dominators.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/IRBuilder.h"
45 #include "llvm/IR/InstIterator.h"
46 #include "llvm/IR/Instruction.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/IntrinsicInst.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/IR/MDBuilder.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/IR/Type.h"
54 #include "llvm/IR/Use.h"
55 #include "llvm/IR/Value.h"
56 #include "llvm/InitializePasses.h"
57 #include "llvm/Pass.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/MathExtras.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include "llvm/Target/TargetMachine.h"
64 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
65 #include "llvm/Transforms/Utils/Cloning.h"
66 #include "llvm/Transforms/Utils/Local.h"
75 using namespace llvm::safestack
;
77 #define DEBUG_TYPE "safe-stack"
81 STATISTIC(NumFunctions
, "Total number of functions");
82 STATISTIC(NumUnsafeStackFunctions
, "Number of functions with unsafe stack");
83 STATISTIC(NumUnsafeStackRestorePointsFunctions
,
84 "Number of functions that use setjmp or exceptions");
86 STATISTIC(NumAllocas
, "Total number of allocas");
87 STATISTIC(NumUnsafeStaticAllocas
, "Number of unsafe static allocas");
88 STATISTIC(NumUnsafeDynamicAllocas
, "Number of unsafe dynamic allocas");
89 STATISTIC(NumUnsafeByValArguments
, "Number of unsafe byval arguments");
90 STATISTIC(NumUnsafeStackRestorePoints
, "Number of setjmps and landingpads");
94 /// Use __safestack_pointer_address even if the platform has a faster way of
95 /// access safe stack pointer.
97 SafeStackUsePointerAddress("safestack-use-pointer-address",
98 cl::init(false), cl::Hidden
);
100 static cl::opt
<bool> ClColoring("safe-stack-coloring",
101 cl::desc("enable safe stack coloring"),
102 cl::Hidden
, cl::init(true));
106 /// The SafeStack pass splits the stack of each function into the safe
107 /// stack, which is only accessed through memory safe dereferences (as
108 /// determined statically), and the unsafe stack, which contains all
109 /// local variables that are accessed in ways that we can't prove to
113 const TargetLoweringBase
&TL
;
114 const DataLayout
&DL
;
123 Value
*UnsafeStackPtr
= nullptr;
125 /// Unsafe stack alignment. Each stack frame must ensure that the stack is
126 /// aligned to this value. We need to re-align the unsafe stack if the
127 /// alignment of any object on the stack exceeds this value.
129 /// 16 seems like a reasonable upper bound on the alignment of objects that we
130 /// might expect to appear on the stack on most common targets.
131 static constexpr Align StackAlignment
= Align::Constant
<16>();
133 /// Return the value of the stack canary.
134 Value
*getStackGuard(IRBuilder
<> &IRB
, Function
&F
);
136 /// Load stack guard from the frame and check if it has changed.
137 void checkStackGuard(IRBuilder
<> &IRB
, Function
&F
, Instruction
&RI
,
138 AllocaInst
*StackGuardSlot
, Value
*StackGuard
);
140 /// Find all static allocas, dynamic allocas, return instructions and
141 /// stack restore points (exception unwind blocks and setjmp calls) in the
142 /// given function and append them to the respective vectors.
143 void findInsts(Function
&F
, SmallVectorImpl
<AllocaInst
*> &StaticAllocas
,
144 SmallVectorImpl
<AllocaInst
*> &DynamicAllocas
,
145 SmallVectorImpl
<Argument
*> &ByValArguments
,
146 SmallVectorImpl
<Instruction
*> &Returns
,
147 SmallVectorImpl
<Instruction
*> &StackRestorePoints
);
149 /// Calculate the allocation size of a given alloca. Returns 0 if the
150 /// size can not be statically determined.
151 uint64_t getStaticAllocaAllocationSize(const AllocaInst
* AI
);
153 /// Allocate space for all static allocas in \p StaticAllocas,
154 /// replace allocas with pointers into the unsafe stack.
156 /// \returns A pointer to the top of the unsafe stack after all unsafe static
157 /// allocas are allocated.
158 Value
*moveStaticAllocasToUnsafeStack(IRBuilder
<> &IRB
, Function
&F
,
159 ArrayRef
<AllocaInst
*> StaticAllocas
,
160 ArrayRef
<Argument
*> ByValArguments
,
161 Instruction
*BasePointer
,
162 AllocaInst
*StackGuardSlot
);
164 /// Generate code to restore the stack after all stack restore points
165 /// in \p StackRestorePoints.
167 /// \returns A local variable in which to maintain the dynamic top of the
168 /// unsafe stack if needed.
170 createStackRestorePoints(IRBuilder
<> &IRB
, Function
&F
,
171 ArrayRef
<Instruction
*> StackRestorePoints
,
172 Value
*StaticTop
, bool NeedDynamicTop
);
174 /// Replace all allocas in \p DynamicAllocas with code to allocate
175 /// space dynamically on the unsafe stack and store the dynamic unsafe stack
176 /// top to \p DynamicTop if non-null.
177 void moveDynamicAllocasToUnsafeStack(Function
&F
, Value
*UnsafeStackPtr
,
178 AllocaInst
*DynamicTop
,
179 ArrayRef
<AllocaInst
*> DynamicAllocas
);
181 bool IsSafeStackAlloca(const Value
*AllocaPtr
, uint64_t AllocaSize
);
183 bool IsMemIntrinsicSafe(const MemIntrinsic
*MI
, const Use
&U
,
184 const Value
*AllocaPtr
, uint64_t AllocaSize
);
185 bool IsAccessSafe(Value
*Addr
, uint64_t Size
, const Value
*AllocaPtr
,
186 uint64_t AllocaSize
);
188 bool ShouldInlinePointerAddress(CallInst
&CI
);
189 void TryInlinePointerAddress();
192 SafeStack(Function
&F
, const TargetLoweringBase
&TL
, const DataLayout
&DL
,
193 DomTreeUpdater
*DTU
, ScalarEvolution
&SE
)
194 : F(F
), TL(TL
), DL(DL
), DTU(DTU
), SE(SE
),
195 StackPtrTy(Type::getInt8PtrTy(F
.getContext())),
196 IntPtrTy(DL
.getIntPtrType(F
.getContext())),
197 Int32Ty(Type::getInt32Ty(F
.getContext())),
198 Int8Ty(Type::getInt8Ty(F
.getContext())) {}
200 // Run the transformation on the associated function.
201 // Returns whether the function was changed.
205 constexpr Align
SafeStack::StackAlignment
;
207 uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst
* AI
) {
208 uint64_t Size
= DL
.getTypeAllocSize(AI
->getAllocatedType());
209 if (AI
->isArrayAllocation()) {
210 auto C
= dyn_cast
<ConstantInt
>(AI
->getArraySize());
213 Size
*= C
->getZExtValue();
218 bool SafeStack::IsAccessSafe(Value
*Addr
, uint64_t AccessSize
,
219 const Value
*AllocaPtr
, uint64_t AllocaSize
) {
220 const SCEV
*AddrExpr
= SE
.getSCEV(Addr
);
221 const auto *Base
= dyn_cast
<SCEVUnknown
>(SE
.getPointerBase(AddrExpr
));
222 if (!Base
|| Base
->getValue() != AllocaPtr
) {
224 dbgs() << "[SafeStack] "
225 << (isa
<AllocaInst
>(AllocaPtr
) ? "Alloca " : "ByValArgument ")
226 << *AllocaPtr
<< "\n"
227 << "SCEV " << *AddrExpr
<< " not directly based on alloca\n");
231 const SCEV
*Expr
= SE
.removePointerBase(AddrExpr
);
232 uint64_t BitWidth
= SE
.getTypeSizeInBits(Expr
->getType());
233 ConstantRange AccessStartRange
= SE
.getUnsignedRange(Expr
);
234 ConstantRange SizeRange
=
235 ConstantRange(APInt(BitWidth
, 0), APInt(BitWidth
, AccessSize
));
236 ConstantRange AccessRange
= AccessStartRange
.add(SizeRange
);
237 ConstantRange AllocaRange
=
238 ConstantRange(APInt(BitWidth
, 0), APInt(BitWidth
, AllocaSize
));
239 bool Safe
= AllocaRange
.contains(AccessRange
);
242 dbgs() << "[SafeStack] "
243 << (isa
<AllocaInst
>(AllocaPtr
) ? "Alloca " : "ByValArgument ")
244 << *AllocaPtr
<< "\n"
245 << " Access " << *Addr
<< "\n"
247 << " U: " << SE
.getUnsignedRange(Expr
)
248 << ", S: " << SE
.getSignedRange(Expr
) << "\n"
249 << " Range " << AccessRange
<< "\n"
250 << " AllocaRange " << AllocaRange
<< "\n"
251 << " " << (Safe
? "safe" : "unsafe") << "\n");
256 bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic
*MI
, const Use
&U
,
257 const Value
*AllocaPtr
,
258 uint64_t AllocaSize
) {
259 if (auto MTI
= dyn_cast
<MemTransferInst
>(MI
)) {
260 if (MTI
->getRawSource() != U
&& MTI
->getRawDest() != U
)
263 if (MI
->getRawDest() != U
)
267 const auto *Len
= dyn_cast
<ConstantInt
>(MI
->getLength());
268 // Non-constant size => unsafe. FIXME: try SCEV getRange.
269 if (!Len
) return false;
270 return IsAccessSafe(U
, Len
->getZExtValue(), AllocaPtr
, AllocaSize
);
273 /// Check whether a given allocation must be put on the safe
274 /// stack or not. The function analyzes all uses of AI and checks whether it is
275 /// only accessed in a memory safe way (as decided statically).
276 bool SafeStack::IsSafeStackAlloca(const Value
*AllocaPtr
, uint64_t AllocaSize
) {
277 // Go through all uses of this alloca and check whether all accesses to the
278 // allocated object are statically known to be memory safe and, hence, the
279 // object can be placed on the safe stack.
280 SmallPtrSet
<const Value
*, 16> Visited
;
281 SmallVector
<const Value
*, 8> WorkList
;
282 WorkList
.push_back(AllocaPtr
);
284 // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
285 while (!WorkList
.empty()) {
286 const Value
*V
= WorkList
.pop_back_val();
287 for (const Use
&UI
: V
->uses()) {
288 auto I
= cast
<const Instruction
>(UI
.getUser());
289 assert(V
== UI
.get());
291 switch (I
->getOpcode()) {
292 case Instruction::Load
:
293 if (!IsAccessSafe(UI
, DL
.getTypeStoreSize(I
->getType()), AllocaPtr
,
298 case Instruction::VAArg
:
299 // "va-arg" from a pointer is safe.
301 case Instruction::Store
:
302 if (V
== I
->getOperand(0)) {
303 // Stored the pointer - conservatively assume it may be unsafe.
305 << "[SafeStack] Unsafe alloca: " << *AllocaPtr
306 << "\n store of address: " << *I
<< "\n");
310 if (!IsAccessSafe(UI
, DL
.getTypeStoreSize(I
->getOperand(0)->getType()),
311 AllocaPtr
, AllocaSize
))
315 case Instruction::Ret
:
319 case Instruction::Call
:
320 case Instruction::Invoke
: {
321 const CallBase
&CS
= *cast
<CallBase
>(I
);
323 if (I
->isLifetimeStartOrEnd())
326 if (const MemIntrinsic
*MI
= dyn_cast
<MemIntrinsic
>(I
)) {
327 if (!IsMemIntrinsicSafe(MI
, UI
, AllocaPtr
, AllocaSize
)) {
329 << "[SafeStack] Unsafe alloca: " << *AllocaPtr
330 << "\n unsafe memintrinsic: " << *I
<< "\n");
336 // LLVM 'nocapture' attribute is only set for arguments whose address
337 // is not stored, passed around, or used in any other non-trivial way.
338 // We assume that passing a pointer to an object as a 'nocapture
339 // readnone' argument is safe.
340 // FIXME: a more precise solution would require an interprocedural
341 // analysis here, which would look at all uses of an argument inside
342 // the function being called.
343 auto B
= CS
.arg_begin(), E
= CS
.arg_end();
344 for (const auto *A
= B
; A
!= E
; ++A
)
346 if (!(CS
.doesNotCapture(A
- B
) && (CS
.doesNotAccessMemory(A
- B
) ||
347 CS
.doesNotAccessMemory()))) {
348 LLVM_DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
349 << "\n unsafe call: " << *I
<< "\n");
356 if (Visited
.insert(I
).second
)
357 WorkList
.push_back(cast
<const Instruction
>(I
));
362 // All uses of the alloca are safe, we can place it on the safe stack.
366 Value
*SafeStack::getStackGuard(IRBuilder
<> &IRB
, Function
&F
) {
367 Value
*StackGuardVar
= TL
.getIRStackGuard(IRB
);
368 Module
*M
= F
.getParent();
370 if (!StackGuardVar
) {
371 TL
.insertSSPDeclarations(*M
);
372 return IRB
.CreateCall(Intrinsic::getDeclaration(M
, Intrinsic::stackguard
));
375 return IRB
.CreateLoad(StackPtrTy
, StackGuardVar
, "StackGuard");
378 void SafeStack::findInsts(Function
&F
,
379 SmallVectorImpl
<AllocaInst
*> &StaticAllocas
,
380 SmallVectorImpl
<AllocaInst
*> &DynamicAllocas
,
381 SmallVectorImpl
<Argument
*> &ByValArguments
,
382 SmallVectorImpl
<Instruction
*> &Returns
,
383 SmallVectorImpl
<Instruction
*> &StackRestorePoints
) {
384 for (Instruction
&I
: instructions(&F
)) {
385 if (auto AI
= dyn_cast
<AllocaInst
>(&I
)) {
388 uint64_t Size
= getStaticAllocaAllocationSize(AI
);
389 if (IsSafeStackAlloca(AI
, Size
))
392 if (AI
->isStaticAlloca()) {
393 ++NumUnsafeStaticAllocas
;
394 StaticAllocas
.push_back(AI
);
396 ++NumUnsafeDynamicAllocas
;
397 DynamicAllocas
.push_back(AI
);
399 } else if (auto RI
= dyn_cast
<ReturnInst
>(&I
)) {
400 if (CallInst
*CI
= I
.getParent()->getTerminatingMustTailCall())
401 Returns
.push_back(CI
);
403 Returns
.push_back(RI
);
404 } else if (auto CI
= dyn_cast
<CallInst
>(&I
)) {
405 // setjmps require stack restore.
406 if (CI
->getCalledFunction() && CI
->canReturnTwice())
407 StackRestorePoints
.push_back(CI
);
408 } else if (auto LP
= dyn_cast
<LandingPadInst
>(&I
)) {
409 // Exception landing pads require stack restore.
410 StackRestorePoints
.push_back(LP
);
411 } else if (auto II
= dyn_cast
<IntrinsicInst
>(&I
)) {
412 if (II
->getIntrinsicID() == Intrinsic::gcroot
)
414 "gcroot intrinsic not compatible with safestack attribute");
417 for (Argument
&Arg
: F
.args()) {
418 if (!Arg
.hasByValAttr())
420 uint64_t Size
= DL
.getTypeStoreSize(Arg
.getParamByValType());
421 if (IsSafeStackAlloca(&Arg
, Size
))
424 ++NumUnsafeByValArguments
;
425 ByValArguments
.push_back(&Arg
);
430 SafeStack::createStackRestorePoints(IRBuilder
<> &IRB
, Function
&F
,
431 ArrayRef
<Instruction
*> StackRestorePoints
,
432 Value
*StaticTop
, bool NeedDynamicTop
) {
433 assert(StaticTop
&& "The stack top isn't set.");
435 if (StackRestorePoints
.empty())
438 // We need the current value of the shadow stack pointer to restore
439 // after longjmp or exception catching.
441 // FIXME: On some platforms this could be handled by the longjmp/exception
444 AllocaInst
*DynamicTop
= nullptr;
445 if (NeedDynamicTop
) {
446 // If we also have dynamic alloca's, the stack pointer value changes
447 // throughout the function. For now we store it in an alloca.
448 DynamicTop
= IRB
.CreateAlloca(StackPtrTy
, /*ArraySize=*/nullptr,
449 "unsafe_stack_dynamic_ptr");
450 IRB
.CreateStore(StaticTop
, DynamicTop
);
453 // Restore current stack pointer after longjmp/exception catch.
454 for (Instruction
*I
: StackRestorePoints
) {
455 ++NumUnsafeStackRestorePoints
;
457 IRB
.SetInsertPoint(I
->getNextNode());
459 DynamicTop
? IRB
.CreateLoad(StackPtrTy
, DynamicTop
) : StaticTop
;
460 IRB
.CreateStore(CurrentTop
, UnsafeStackPtr
);
466 void SafeStack::checkStackGuard(IRBuilder
<> &IRB
, Function
&F
, Instruction
&RI
,
467 AllocaInst
*StackGuardSlot
, Value
*StackGuard
) {
468 Value
*V
= IRB
.CreateLoad(StackPtrTy
, StackGuardSlot
);
469 Value
*Cmp
= IRB
.CreateICmpNE(StackGuard
, V
);
471 auto SuccessProb
= BranchProbabilityInfo::getBranchProbStackProtector(true);
472 auto FailureProb
= BranchProbabilityInfo::getBranchProbStackProtector(false);
473 MDNode
*Weights
= MDBuilder(F
.getContext())
474 .createBranchWeights(SuccessProb
.getNumerator(),
475 FailureProb
.getNumerator());
476 Instruction
*CheckTerm
=
477 SplitBlockAndInsertIfThen(Cmp
, &RI
, /* Unreachable */ true, Weights
, DTU
);
478 IRBuilder
<> IRBFail(CheckTerm
);
479 // FIXME: respect -fsanitize-trap / -ftrap-function here?
480 FunctionCallee StackChkFail
=
481 F
.getParent()->getOrInsertFunction("__stack_chk_fail", IRB
.getVoidTy());
482 IRBFail
.CreateCall(StackChkFail
, {});
485 /// We explicitly compute and set the unsafe stack layout for all unsafe
486 /// static alloca instructions. We save the unsafe "base pointer" in the
487 /// prologue into a local variable and restore it in the epilogue.
488 Value
*SafeStack::moveStaticAllocasToUnsafeStack(
489 IRBuilder
<> &IRB
, Function
&F
, ArrayRef
<AllocaInst
*> StaticAllocas
,
490 ArrayRef
<Argument
*> ByValArguments
, Instruction
*BasePointer
,
491 AllocaInst
*StackGuardSlot
) {
492 if (StaticAllocas
.empty() && ByValArguments
.empty())
495 DIBuilder
DIB(*F
.getParent());
497 StackLifetime
SSC(F
, StaticAllocas
, StackLifetime::LivenessType::May
);
498 static const StackLifetime::LiveRange
NoColoringRange(1, true);
502 for (const auto *I
: SSC
.getMarkers()) {
503 auto *Op
= dyn_cast
<Instruction
>(I
->getOperand(1));
504 const_cast<IntrinsicInst
*>(I
)->eraseFromParent();
505 // Remove the operand bitcast, too, if it has no more uses left.
506 if (Op
&& Op
->use_empty())
507 Op
->eraseFromParent();
510 // Unsafe stack always grows down.
511 StackLayout
SSL(StackAlignment
);
512 if (StackGuardSlot
) {
513 Type
*Ty
= StackGuardSlot
->getAllocatedType();
514 Align Align
= std::max(DL
.getPrefTypeAlign(Ty
), StackGuardSlot
->getAlign());
515 SSL
.addObject(StackGuardSlot
, getStaticAllocaAllocationSize(StackGuardSlot
),
516 Align
, SSC
.getFullLiveRange());
519 for (Argument
*Arg
: ByValArguments
) {
520 Type
*Ty
= Arg
->getParamByValType();
521 uint64_t Size
= DL
.getTypeStoreSize(Ty
);
523 Size
= 1; // Don't create zero-sized stack objects.
525 // Ensure the object is properly aligned.
526 Align Align
= DL
.getPrefTypeAlign(Ty
);
527 if (auto A
= Arg
->getParamAlign())
528 Align
= std::max(Align
, *A
);
529 SSL
.addObject(Arg
, Size
, Align
, SSC
.getFullLiveRange());
532 for (AllocaInst
*AI
: StaticAllocas
) {
533 Type
*Ty
= AI
->getAllocatedType();
534 uint64_t Size
= getStaticAllocaAllocationSize(AI
);
536 Size
= 1; // Don't create zero-sized stack objects.
538 // Ensure the object is properly aligned.
539 Align Align
= std::max(DL
.getPrefTypeAlign(Ty
), AI
->getAlign());
541 SSL
.addObject(AI
, Size
, Align
,
542 ClColoring
? SSC
.getLiveRange(AI
) : NoColoringRange
);
546 Align FrameAlignment
= SSL
.getFrameAlignment();
548 // FIXME: tell SSL that we start at a less-then-MaxAlignment aligned location
550 if (FrameAlignment
> StackAlignment
) {
551 // Re-align the base pointer according to the max requested alignment.
552 IRB
.SetInsertPoint(BasePointer
->getNextNode());
553 BasePointer
= cast
<Instruction
>(IRB
.CreateIntToPtr(
555 IRB
.CreatePtrToInt(BasePointer
, IntPtrTy
),
556 ConstantInt::get(IntPtrTy
, ~(FrameAlignment
.value() - 1))),
560 IRB
.SetInsertPoint(BasePointer
->getNextNode());
562 if (StackGuardSlot
) {
563 unsigned Offset
= SSL
.getObjectOffset(StackGuardSlot
);
564 Value
*Off
= IRB
.CreateGEP(Int8Ty
, BasePointer
, // BasePointer is i8*
565 ConstantInt::get(Int32Ty
, -Offset
));
567 IRB
.CreateBitCast(Off
, StackGuardSlot
->getType(), "StackGuardSlot");
569 // Replace alloc with the new location.
570 StackGuardSlot
->replaceAllUsesWith(NewAI
);
571 StackGuardSlot
->eraseFromParent();
574 for (Argument
*Arg
: ByValArguments
) {
575 unsigned Offset
= SSL
.getObjectOffset(Arg
);
576 MaybeAlign
Align(SSL
.getObjectAlignment(Arg
));
577 Type
*Ty
= Arg
->getParamByValType();
579 uint64_t Size
= DL
.getTypeStoreSize(Ty
);
581 Size
= 1; // Don't create zero-sized stack objects.
583 Value
*Off
= IRB
.CreateGEP(Int8Ty
, BasePointer
, // BasePointer is i8*
584 ConstantInt::get(Int32Ty
, -Offset
));
585 Value
*NewArg
= IRB
.CreateBitCast(Off
, Arg
->getType(),
586 Arg
->getName() + ".unsafe-byval");
588 // Replace alloc with the new location.
589 replaceDbgDeclare(Arg
, BasePointer
, DIB
, DIExpression::ApplyOffset
,
591 Arg
->replaceAllUsesWith(NewArg
);
592 IRB
.SetInsertPoint(cast
<Instruction
>(NewArg
)->getNextNode());
593 IRB
.CreateMemCpy(Off
, Align
, Arg
, Arg
->getParamAlign(), Size
);
596 // Allocate space for every unsafe static AllocaInst on the unsafe stack.
597 for (AllocaInst
*AI
: StaticAllocas
) {
598 IRB
.SetInsertPoint(AI
);
599 unsigned Offset
= SSL
.getObjectOffset(AI
);
601 replaceDbgDeclare(AI
, BasePointer
, DIB
, DIExpression::ApplyOffset
, -Offset
);
602 replaceDbgValueForAlloca(AI
, BasePointer
, DIB
, -Offset
);
604 // Replace uses of the alloca with the new location.
605 // Insert address calculation close to each use to work around PR27844.
606 std::string Name
= std::string(AI
->getName()) + ".unsafe";
607 while (!AI
->use_empty()) {
608 Use
&U
= *AI
->use_begin();
609 Instruction
*User
= cast
<Instruction
>(U
.getUser());
611 Instruction
*InsertBefore
;
612 if (auto *PHI
= dyn_cast
<PHINode
>(User
))
613 InsertBefore
= PHI
->getIncomingBlock(U
)->getTerminator();
617 IRBuilder
<> IRBUser(InsertBefore
);
618 Value
*Off
= IRBUser
.CreateGEP(Int8Ty
, BasePointer
, // BasePointer is i8*
619 ConstantInt::get(Int32Ty
, -Offset
));
620 Value
*Replacement
= IRBUser
.CreateBitCast(Off
, AI
->getType(), Name
);
622 if (auto *PHI
= dyn_cast
<PHINode
>(User
))
623 // PHI nodes may have multiple incoming edges from the same BB (why??),
624 // all must be updated at once with the same incoming value.
625 PHI
->setIncomingValueForBlock(PHI
->getIncomingBlock(U
), Replacement
);
630 AI
->eraseFromParent();
633 // Re-align BasePointer so that our callees would see it aligned as
635 // FIXME: no need to update BasePointer in leaf functions.
636 unsigned FrameSize
= alignTo(SSL
.getFrameSize(), StackAlignment
);
638 MDBuilder
MDB(F
.getContext());
639 SmallVector
<Metadata
*, 2> Data
;
640 Data
.push_back(MDB
.createString("unsafe-stack-size"));
641 Data
.push_back(MDB
.createConstant(ConstantInt::get(Int32Ty
, FrameSize
)));
642 MDNode
*MD
= MDTuple::get(F
.getContext(), Data
);
643 F
.setMetadata(LLVMContext::MD_annotation
, MD
);
645 // Update shadow stack pointer in the function epilogue.
646 IRB
.SetInsertPoint(BasePointer
->getNextNode());
649 IRB
.CreateGEP(Int8Ty
, BasePointer
, ConstantInt::get(Int32Ty
, -FrameSize
),
650 "unsafe_stack_static_top");
651 IRB
.CreateStore(StaticTop
, UnsafeStackPtr
);
655 void SafeStack::moveDynamicAllocasToUnsafeStack(
656 Function
&F
, Value
*UnsafeStackPtr
, AllocaInst
*DynamicTop
,
657 ArrayRef
<AllocaInst
*> DynamicAllocas
) {
658 DIBuilder
DIB(*F
.getParent());
660 for (AllocaInst
*AI
: DynamicAllocas
) {
663 // Compute the new SP value (after AI).
664 Value
*ArraySize
= AI
->getArraySize();
665 if (ArraySize
->getType() != IntPtrTy
)
666 ArraySize
= IRB
.CreateIntCast(ArraySize
, IntPtrTy
, false);
668 Type
*Ty
= AI
->getAllocatedType();
669 uint64_t TySize
= DL
.getTypeAllocSize(Ty
);
670 Value
*Size
= IRB
.CreateMul(ArraySize
, ConstantInt::get(IntPtrTy
, TySize
));
672 Value
*SP
= IRB
.CreatePtrToInt(IRB
.CreateLoad(StackPtrTy
, UnsafeStackPtr
),
674 SP
= IRB
.CreateSub(SP
, Size
);
676 // Align the SP value to satisfy the AllocaInst, type and stack alignments.
677 auto Align
= std::max(std::max(DL
.getPrefTypeAlign(Ty
), AI
->getAlign()),
680 Value
*NewTop
= IRB
.CreateIntToPtr(
682 ConstantInt::get(IntPtrTy
, ~uint64_t(Align
.value() - 1))),
685 // Save the stack pointer.
686 IRB
.CreateStore(NewTop
, UnsafeStackPtr
);
688 IRB
.CreateStore(NewTop
, DynamicTop
);
690 Value
*NewAI
= IRB
.CreatePointerCast(NewTop
, AI
->getType());
691 if (AI
->hasName() && isa
<Instruction
>(NewAI
))
694 replaceDbgDeclare(AI
, NewAI
, DIB
, DIExpression::ApplyOffset
, 0);
695 AI
->replaceAllUsesWith(NewAI
);
696 AI
->eraseFromParent();
699 if (!DynamicAllocas
.empty()) {
700 // Now go through the instructions again, replacing stacksave/stackrestore.
701 for (Instruction
&I
: llvm::make_early_inc_range(instructions(&F
))) {
702 auto *II
= dyn_cast
<IntrinsicInst
>(&I
);
706 if (II
->getIntrinsicID() == Intrinsic::stacksave
) {
708 Instruction
*LI
= IRB
.CreateLoad(StackPtrTy
, UnsafeStackPtr
);
710 II
->replaceAllUsesWith(LI
);
711 II
->eraseFromParent();
712 } else if (II
->getIntrinsicID() == Intrinsic::stackrestore
) {
714 Instruction
*SI
= IRB
.CreateStore(II
->getArgOperand(0), UnsafeStackPtr
);
716 assert(II
->use_empty());
717 II
->eraseFromParent();
723 bool SafeStack::ShouldInlinePointerAddress(CallInst
&CI
) {
724 Function
*Callee
= CI
.getCalledFunction();
725 if (CI
.hasFnAttr(Attribute::AlwaysInline
) &&
726 isInlineViable(*Callee
).isSuccess())
728 if (Callee
->isInterposable() || Callee
->hasFnAttribute(Attribute::NoInline
) ||
734 void SafeStack::TryInlinePointerAddress() {
735 auto *CI
= dyn_cast
<CallInst
>(UnsafeStackPtr
);
742 Function
*Callee
= CI
->getCalledFunction();
743 if (!Callee
|| Callee
->isDeclaration())
746 if (!ShouldInlinePointerAddress(*CI
))
749 InlineFunctionInfo IFI
;
750 InlineFunction(*CI
, IFI
);
753 bool SafeStack::run() {
754 assert(F
.hasFnAttribute(Attribute::SafeStack
) &&
755 "Can't run SafeStack on a function without the attribute");
756 assert(!F
.isDeclaration() && "Can't run SafeStack on a function declaration");
760 SmallVector
<AllocaInst
*, 16> StaticAllocas
;
761 SmallVector
<AllocaInst
*, 4> DynamicAllocas
;
762 SmallVector
<Argument
*, 4> ByValArguments
;
763 SmallVector
<Instruction
*, 4> Returns
;
765 // Collect all points where stack gets unwound and needs to be restored
766 // This is only necessary because the runtime (setjmp and unwind code) is
767 // not aware of the unsafe stack and won't unwind/restore it properly.
768 // To work around this problem without changing the runtime, we insert
769 // instrumentation to restore the unsafe stack pointer when necessary.
770 SmallVector
<Instruction
*, 4> StackRestorePoints
;
772 // Find all static and dynamic alloca instructions that must be moved to the
773 // unsafe stack, all return instructions and stack restore points.
774 findInsts(F
, StaticAllocas
, DynamicAllocas
, ByValArguments
, Returns
,
777 if (StaticAllocas
.empty() && DynamicAllocas
.empty() &&
778 ByValArguments
.empty() && StackRestorePoints
.empty())
779 return false; // Nothing to do in this function.
781 if (!StaticAllocas
.empty() || !DynamicAllocas
.empty() ||
782 !ByValArguments
.empty())
783 ++NumUnsafeStackFunctions
; // This function has the unsafe stack.
785 if (!StackRestorePoints
.empty())
786 ++NumUnsafeStackRestorePointsFunctions
;
788 IRBuilder
<> IRB(&F
.front(), F
.begin()->getFirstInsertionPt());
789 // Calls must always have a debug location, or else inlining breaks. So
790 // we explicitly set a artificial debug location here.
791 if (DISubprogram
*SP
= F
.getSubprogram())
792 IRB
.SetCurrentDebugLocation(
793 DILocation::get(SP
->getContext(), SP
->getScopeLine(), 0, SP
));
794 if (SafeStackUsePointerAddress
) {
795 FunctionCallee Fn
= F
.getParent()->getOrInsertFunction(
796 "__safestack_pointer_address", StackPtrTy
->getPointerTo(0));
797 UnsafeStackPtr
= IRB
.CreateCall(Fn
);
799 UnsafeStackPtr
= TL
.getSafeStackPointerLocation(IRB
);
802 // Load the current stack pointer (we'll also use it as a base pointer).
803 // FIXME: use a dedicated register for it ?
804 Instruction
*BasePointer
=
805 IRB
.CreateLoad(StackPtrTy
, UnsafeStackPtr
, false, "unsafe_stack_ptr");
806 assert(BasePointer
->getType() == StackPtrTy
);
808 AllocaInst
*StackGuardSlot
= nullptr;
809 // FIXME: implement weaker forms of stack protector.
810 if (F
.hasFnAttribute(Attribute::StackProtect
) ||
811 F
.hasFnAttribute(Attribute::StackProtectStrong
) ||
812 F
.hasFnAttribute(Attribute::StackProtectReq
)) {
813 Value
*StackGuard
= getStackGuard(IRB
, F
);
814 StackGuardSlot
= IRB
.CreateAlloca(StackPtrTy
, nullptr);
815 IRB
.CreateStore(StackGuard
, StackGuardSlot
);
817 for (Instruction
*RI
: Returns
) {
818 IRBuilder
<> IRBRet(RI
);
819 checkStackGuard(IRBRet
, F
, *RI
, StackGuardSlot
, StackGuard
);
823 // The top of the unsafe stack after all unsafe static allocas are
825 Value
*StaticTop
= moveStaticAllocasToUnsafeStack(
826 IRB
, F
, StaticAllocas
, ByValArguments
, BasePointer
, StackGuardSlot
);
828 // Safe stack object that stores the current unsafe stack top. It is updated
829 // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
830 // This is only needed if we need to restore stack pointer after longjmp
831 // or exceptions, and we have dynamic allocations.
832 // FIXME: a better alternative might be to store the unsafe stack pointer
833 // before setjmp / invoke instructions.
834 AllocaInst
*DynamicTop
= createStackRestorePoints(
835 IRB
, F
, StackRestorePoints
, StaticTop
, !DynamicAllocas
.empty());
837 // Handle dynamic allocas.
838 moveDynamicAllocasToUnsafeStack(F
, UnsafeStackPtr
, DynamicTop
,
841 // Restore the unsafe stack pointer before each return.
842 for (Instruction
*RI
: Returns
) {
843 IRB
.SetInsertPoint(RI
);
844 IRB
.CreateStore(BasePointer
, UnsafeStackPtr
);
847 TryInlinePointerAddress();
849 LLVM_DEBUG(dbgs() << "[SafeStack] safestack applied\n");
853 class SafeStackLegacyPass
: public FunctionPass
{
854 const TargetMachine
*TM
= nullptr;
857 static char ID
; // Pass identification, replacement for typeid..
859 SafeStackLegacyPass() : FunctionPass(ID
) {
860 initializeSafeStackLegacyPassPass(*PassRegistry::getPassRegistry());
863 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
864 AU
.addRequired
<TargetPassConfig
>();
865 AU
.addRequired
<TargetLibraryInfoWrapperPass
>();
866 AU
.addRequired
<AssumptionCacheTracker
>();
867 AU
.addPreserved
<DominatorTreeWrapperPass
>();
870 bool runOnFunction(Function
&F
) override
{
871 LLVM_DEBUG(dbgs() << "[SafeStack] Function: " << F
.getName() << "\n");
873 if (!F
.hasFnAttribute(Attribute::SafeStack
)) {
874 LLVM_DEBUG(dbgs() << "[SafeStack] safestack is not requested"
875 " for this function\n");
879 if (F
.isDeclaration()) {
880 LLVM_DEBUG(dbgs() << "[SafeStack] function definition"
881 " is not available\n");
885 TM
= &getAnalysis
<TargetPassConfig
>().getTM
<TargetMachine
>();
886 auto *TL
= TM
->getSubtargetImpl(F
)->getTargetLowering();
888 report_fatal_error("TargetLowering instance is required");
890 auto *DL
= &F
.getParent()->getDataLayout();
891 auto &TLI
= getAnalysis
<TargetLibraryInfoWrapperPass
>().getTLI(F
);
892 auto &ACT
= getAnalysis
<AssumptionCacheTracker
>().getAssumptionCache(F
);
894 // Compute DT and LI only for functions that have the attribute.
895 // This is only useful because the legacy pass manager doesn't let us
896 // compute analyzes lazily.
899 bool ShouldPreserveDominatorTree
;
900 std::optional
<DominatorTree
> LazilyComputedDomTree
;
902 // Do we already have a DominatorTree avaliable from the previous pass?
903 // Note that we should *NOT* require it, to avoid the case where we end up
904 // not needing it, but the legacy PM would have computed it for us anyways.
905 if (auto *DTWP
= getAnalysisIfAvailable
<DominatorTreeWrapperPass
>()) {
906 DT
= &DTWP
->getDomTree();
907 ShouldPreserveDominatorTree
= true;
909 // Otherwise, we need to compute it.
910 LazilyComputedDomTree
.emplace(F
);
911 DT
= &*LazilyComputedDomTree
;
912 ShouldPreserveDominatorTree
= false;
915 // Likewise, lazily compute loop info.
918 DomTreeUpdater
DTU(DT
, DomTreeUpdater::UpdateStrategy::Lazy
);
920 ScalarEvolution
SE(F
, TLI
, ACT
, *DT
, LI
);
922 return SafeStack(F
, *TL
, *DL
, ShouldPreserveDominatorTree
? &DTU
: nullptr,
928 } // end anonymous namespace
930 char SafeStackLegacyPass::ID
= 0;
932 INITIALIZE_PASS_BEGIN(SafeStackLegacyPass
, DEBUG_TYPE
,
933 "Safe Stack instrumentation pass", false, false)
934 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig
)
935 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass
)
936 INITIALIZE_PASS_END(SafeStackLegacyPass
, DEBUG_TYPE
,
937 "Safe Stack instrumentation pass", false, false)
939 FunctionPass
*llvm::createSafeStackPass() { return new SafeStackLegacyPass(); }