53 using namespace llvm::safestack;
55 #define DEBUG_TYPE "safe-stack"
59 STATISTIC(NumFunctions,
"Total number of functions");
60 STATISTIC(NumUnsafeStackFunctions,
"Number of functions with unsafe stack");
61 STATISTIC(NumUnsafeStackRestorePointsFunctions,
62 "Number of functions that use setjmp or exceptions");
64 STATISTIC(NumAllocas,
"Total number of allocas");
65 STATISTIC(NumUnsafeStaticAllocas,
"Number of unsafe static allocas");
66 STATISTIC(NumUnsafeDynamicAllocas,
"Number of unsafe dynamic allocas");
67 STATISTIC(NumUnsafeByValArguments,
"Number of unsafe byval arguments");
68 STATISTIC(NumUnsafeStackRestorePoints,
"Number of setjmps and landingpads");
79 const Value *AllocaPtr;
87 return SE.getZero(Expr->
getType());
108 Value *UnsafeStackPtr =
nullptr;
116 enum { StackAlignment = 16 };
136 uint64_t getStaticAllocaAllocationSize(
const AllocaInst* AI);
159 Value *StaticTop,
bool NeedDynamicTop);
164 void moveDynamicAllocasToUnsafeStack(
Function &
F,
Value *UnsafeStackPtr,
168 bool IsSafeStackAlloca(
const Value *AllocaPtr, uint64_t AllocaSize);
171 const Value *AllocaPtr, uint64_t AllocaSize);
172 bool IsAccessSafe(
Value *Addr, uint64_t
Size,
const Value *AllocaPtr,
173 uint64_t AllocaSize);
178 : F(F), TL(TL), DL(DL), SE(SE),
179 StackPtrTy(
Type::getInt8PtrTy(F.getContext())),
180 IntPtrTy(DL.getIntPtrType(F.getContext())),
182 Int8Ty(
Type::getInt8Ty(F.getContext())) {}
189 uint64_t SafeStack::getStaticAllocaAllocationSize(
const AllocaInst* AI) {
195 Size *=
C->getZExtValue();
200 bool SafeStack::IsAccessSafe(
Value *Addr, uint64_t AccessSize,
201 const Value *AllocaPtr, uint64_t AllocaSize) {
202 AllocaOffsetRewriter
Rewriter(SE, AllocaPtr);
205 uint64_t BitWidth = SE.getTypeSizeInBits(Expr->
getType());
212 bool Safe = AllocaRange.
contains(AccessRange);
215 << (isa<AllocaInst>(AllocaPtr) ?
"Alloca " :
"ByValArgument ")
216 << *AllocaPtr <<
"\n"
217 <<
" Access " << *Addr <<
"\n"
219 <<
" U: " << SE.getUnsignedRange(Expr)
220 <<
", S: " << SE.getSignedRange(Expr) <<
"\n"
221 <<
" Range " << AccessRange <<
"\n"
222 <<
" AllocaRange " << AllocaRange <<
"\n"
223 <<
" " << (Safe ?
"safe" :
"unsafe") <<
"\n");
229 const Value *AllocaPtr,
230 uint64_t AllocaSize) {
235 if (!Len)
return false;
236 return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
242 bool SafeStack::IsSafeStackAlloca(
const Value *AllocaPtr, uint64_t AllocaSize) {
251 while (!WorkList.
empty()) {
253 for (
const Use &UI : V->
uses()) {
254 auto I = cast<const Instruction>(UI.getUser());
257 switch (
I->getOpcode()) {
264 case Instruction::VAArg:
268 if (V ==
I->getOperand(0)) {
270 DEBUG(
dbgs() <<
"[SafeStack] Unsafe alloca: " << *AllocaPtr
271 <<
"\n store of address: " << *
I <<
"\n");
276 AllocaPtr, AllocaSize))
286 case Instruction::Invoke: {
290 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
291 II->getIntrinsicID() == Intrinsic::lifetime_end)
296 if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
297 DEBUG(
dbgs() <<
"[SafeStack] Unsafe alloca: " << *AllocaPtr
298 <<
"\n unsafe memintrinsic: " << *
I
315 if (!(
CS.doesNotCapture(
A - B) && (
CS.doesNotAccessMemory(
A - B) ||
316 CS.doesNotAccessMemory()))) {
317 DEBUG(
dbgs() <<
"[SafeStack] Unsafe alloca: " << *AllocaPtr
318 <<
"\n unsafe call: " << *
I <<
"\n");
326 WorkList.
push_back(cast<const Instruction>(
I));
336 Value *StackGuardVar = TL.getIRStackGuard(IRB);
340 return IRB.
CreateLoad(StackGuardVar,
"StackGuard");
343 void SafeStack::findInsts(
Function &F,
350 if (
auto AI = dyn_cast<AllocaInst>(&
I)) {
353 uint64_t Size = getStaticAllocaAllocationSize(AI);
354 if (IsSafeStackAlloca(AI, Size))
358 ++NumUnsafeStaticAllocas;
361 ++NumUnsafeDynamicAllocas;
364 }
else if (
auto RI = dyn_cast<ReturnInst>(&
I)) {
366 }
else if (
auto CI = dyn_cast<CallInst>(&
I)) {
368 if (CI->getCalledFunction() && CI->canReturnTwice())
370 }
else if (
auto LP = dyn_cast<LandingPadInst>(&
I)) {
373 }
else if (
auto II = dyn_cast<IntrinsicInst>(&
I)) {
374 if (II->getIntrinsicID() == Intrinsic::gcroot)
376 "gcroot intrinsic not compatible with safestack attribute");
380 if (!Arg.hasByValAttr())
384 if (IsSafeStackAlloca(&Arg, Size))
387 ++NumUnsafeByValArguments;
395 Value *StaticTop,
bool NeedDynamicTop) {
396 assert(StaticTop &&
"The stack top isn't set.");
398 if (StackRestorePoints.
empty())
408 if (NeedDynamicTop) {
412 "unsafe_stack_dynamic_ptr");
418 ++NumUnsafeStackRestorePoints;
421 Value *CurrentTop = DynamicTop ? IRB.
CreateLoad(DynamicTop) : StaticTop;
436 .createBranchWeights(SuccessProb.getNumerator(),
437 FailureProb.getNumerator());
445 IRBFail.CreateCall(StackChkFail, {});
451 Value *SafeStack::moveStaticAllocasToUnsafeStack(
455 if (StaticAllocas.
empty() && ByValArguments.
empty())
462 SSC.removeAllMarkers();
466 if (StackGuardSlot) {
470 SSL.addObject(StackGuardSlot, getStaticAllocaAllocationSize(StackGuardSlot),
471 Align, SSC.getFullLiveRange());
474 for (
Argument *Arg : ByValArguments) {
482 Arg->getParamAlignment());
483 SSL.addObject(Arg, Size, Align, SSC.getFullLiveRange());
488 uint64_t Size = getStaticAllocaAllocationSize(AI);
496 SSL.addObject(AI, Size, Align, SSC.getLiveRange(AI));
500 unsigned FrameAlignment = SSL.getFrameAlignment();
504 if (FrameAlignment > StackAlignment) {
516 if (StackGuardSlot) {
517 unsigned Offset = SSL.getObjectOffset(StackGuardSlot);
528 for (
Argument *Arg : ByValArguments) {
529 unsigned Offset = SSL.getObjectOffset(Arg);
539 Arg->getName() +
".unsafe-byval");
544 Arg->replaceAllUsesWith(NewArg);
546 IRB.
CreateMemCpy(Off, Arg, Size, Arg->getParamAlignment());
552 unsigned Offset = SSL.getObjectOffset(AI);
554 uint64_t Size = getStaticAllocaAllocationSize(AI);
563 std::string
Name = std::string(AI->
getName()) +
".unsafe";
569 if (
auto *PHI = dyn_cast<PHINode>(User))
570 InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
575 Value *Off = IRBUser.CreateGEP(BasePointer,
579 if (
auto *PHI = dyn_cast<PHINode>(User)) {
582 auto *BB = PHI->getIncomingBlock(U);
583 for (
unsigned I = 0;
I < PHI->getNumIncomingValues(); ++
I)
584 if (PHI->getIncomingBlock(
I) == BB)
585 PHI->setIncomingValue(
I, Replacement);
597 unsigned FrameSize =
alignTo(SSL.getFrameSize(), StackAlignment);
604 "unsafe_stack_static_top");
609 void SafeStack::moveDynamicAllocasToUnsafeStack(
619 if (ArraySize->
getType() != IntPtrTy)
632 (
unsigned)StackAlignment);
635 Value *NewTop = IRB.CreateIntToPtr(
636 IRB.CreateAnd(SP,
ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
640 IRB.CreateStore(NewTop, UnsafeStackPtr);
642 IRB.CreateStore(NewTop, DynamicTop);
644 Value *NewAI = IRB.CreatePointerCast(NewTop, AI->
getType());
649 AI->replaceAllUsesWith(NewAI);
650 AI->eraseFromParent();
653 if (!DynamicAllocas.empty()) {
661 if (II->getIntrinsicID() == Intrinsic::stacksave) {
665 II->replaceAllUsesWith(LI);
666 II->eraseFromParent();
667 }
else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
672 II->eraseFromParent();
678 bool SafeStack::run() {
680 "Can't run SafeStack on a function without the attribute");
699 findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
702 if (StaticAllocas.
empty() && DynamicAllocas.
empty() &&
703 ByValArguments.
empty() && StackRestorePoints.
empty())
706 if (!StaticAllocas.
empty() || !DynamicAllocas.
empty() ||
707 !ByValArguments.
empty())
708 ++NumUnsafeStackFunctions;
710 if (!StackRestorePoints.
empty())
711 ++NumUnsafeStackRestorePointsFunctions;
714 UnsafeStackPtr = TL.getSafeStackPointerLocation(IRB);
719 IRB.
CreateLoad(UnsafeStackPtr,
false,
"unsafe_stack_ptr");
733 checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
740 moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, ByValArguments,
741 Returns, BasePointer, StackGuardSlot);
749 AllocaInst *DynamicTop = createStackRestorePoints(
750 IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.
empty());
753 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
762 DEBUG(
dbgs() <<
"[SafeStack] safestack applied\n");
781 bool runOnFunction(
Function &F)
override {
785 DEBUG(
dbgs() <<
"[SafeStack] safestack is not requested"
786 " for this function\n");
791 DEBUG(
dbgs() <<
"[SafeStack] function definition"
792 " is not available\n");
796 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
797 auto *TL =
TM->getSubtargetImpl(F)->getTargetLowering();
802 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
803 auto &ACT = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
816 return SafeStack(F, *TL, *DL, SE).run();
824 "Safe Stack instrumentation pass",
false,
false)
Return a value (possibly void), from a function.
User::const_op_iterator arg_iterator
The type of iterator to use when looping over actual arguments at this call site. ...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, bool Deref, int Offset=0)
Replaces llvm.dbg.declare instruction when the alloca it describes is replaced with a new value...
Safe Stack instrumentation pass
iterator_range< use_iterator > uses()
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
This class represents an incoming formal argument to a Function.
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
void replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, int Offset=0)
Replaces multiple llvm.dbg.value instructions when the alloca it describes is replaced with a new val...
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
STATISTIC(NumFunctions,"Total number of functions")
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Compute live ranges of allocas.
unsigned getPrefTypeAlignment(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
The main scalar evolution driver.
An immutable pass that tracks lazily created AssumptionCache objects.
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Type * getPointerElementType() const
StringRef getName() const
Return a constant reference to the value's name.
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
inst_iterator inst_begin(Function *F)
A Use represents the edge between a Value definition and its users.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
FunctionPass * createSafeStackPass()
This pass splits the stack into a safe stack and an unsafe stack to protect against stack-based overf...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Target-Independent Code Generator Pass Configuration Options.
Type * getVoidTy()
Fetch the type representing void.
LLVM_NODISCARD bool empty() const
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
LoadInst * CreateLoad(Value *Ptr, const char *Name)
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
The instances of the Type class are immutable: once they are created, they are never changed...
Type * getType() const
Return the LLVM type of this SCEV expression.
Constant * getOrInsertGlobal(StringRef Name, Type *Ty)
Look up the specified global in the module symbol table.
This is an important base class in LLVM.
PointerType * getType() const
Overload to return most specific pointer type.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Value * getRawDest() const
Compute the layout of an unsafe stack frame.
Represent the analysis usage information of a pass.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
bool empty() const
empty - Check if the array is empty.
bool replaceDbgDeclare(Value *Address, Value *NewAddress, Instruction *InsertBefore, DIBuilder &Builder, bool Deref, int Offset)
Replaces llvm.dbg.declare instruction when the address it describes is replaced with a new value...
static wasm::ValType getType(const TargetRegisterClass *RC)
ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
This is the common base class for memset/memcpy/memmove.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
This class represents a range of values.
TerminatorInst * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
Value * getLength() const
LLVM_NODISCARD T pop_back_val()
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
LLVM_NODISCARD bool isa(const Y &Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Value * CreateGEP(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Class for arbitrary precision integers.
void initializeSafeStackLegacyPassPass(PassRegistry &)
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
Virtual Register Rewriter
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
CallInst * CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memcpy between the specified pointers.
This class represents an analyzed expression in the program.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Establish a view to a call site for examination.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock & front() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
Safe Stack instrumentation false
const Value * getArraySize() const
Get the number of elements allocated.
Primary interface to the complete machine description for the target machine.
inst_iterator inst_end(Function *F)
inst_range instructions(Function *F)
INITIALIZE_PASS_BEGIN(SafeStackLegacyPass, DEBUG_TYPE,"Safe Stack instrumentation pass", false, false) INITIALIZE_PASS_END(SafeStackLegacyPass
static Value * getStackGuard(const TargetLoweringBase *TLI, Module *M, IRBuilder<> &B, bool *SupportsSelectionDAGSP=nullptr)
Create a stack guard loading and populate whether SelectionDAG SSP is supported.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
This visitor recursively visits a SCEV expression and re-writes it.
static BranchProbability getBranchProbStackProtector(bool IsLikely)
iterator_range< arg_iterator > args()
A wrapper class for inspecting calls to intrinsic functions.
This file describes how to lower LLVM code to machine code.
an instruction to allocate memory on the stack