53 #define DEBUG_TYPE "stack-protector"
55 STATISTIC(NumFunProtected,
"Number of functions protected");
56 STATISTIC(NumAddrTaken,
"Number of local variables that have their address"
65 "Insert stack protectors",
false,
true)
83 if (I != Layout.
end()) {
91 if (I == Layout.
end())
92 Layout.
insert(std::make_pair(To, Kind));
107 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
109 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
120 if (!RequiresStackProtector())
132 return InsertStackProtectors();
138 bool StackProtector::ContainsProtectableArray(
Type *Ty,
bool &IsLarge,
140 bool InStruct)
const {
143 if (
ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
144 if (!AT->getElementType()->isIntegerTy(8)) {
149 if (!Strong && (InStruct || !Trip.
isOSDarwin()))
155 if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
169 bool NeedsProtector =
false;
173 if (ContainsProtectableArray(*
I, IsLarge, Strong,
true)) {
179 NeedsProtector =
true;
182 return NeedsProtector;
185 bool StackProtector::HasAddressTaken(
const Instruction *AI) {
187 if (
const StoreInst *SI = dyn_cast<StoreInst>(U)) {
188 if (AI ==
SI->getValueOperand())
190 }
else if (
const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
191 if (AI ==
SI->getOperand(0))
193 }
else if (isa<CallInst>(U)) {
195 }
else if (isa<InvokeInst>(U)) {
197 }
else if (
const SelectInst *SI = dyn_cast<SelectInst>(U)) {
198 if (HasAddressTaken(SI))
200 }
else if (
const PHINode *PN = dyn_cast<PHINode>(U)) {
203 if (VisitedPHIs.insert(PN).second)
204 if (HasAddressTaken(PN))
207 if (HasAddressTaken(
GEP))
209 }
else if (
const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
210 if (HasAddressTaken(BI))
230 bool StackProtector::RequiresStackProtector() {
232 bool NeedsProtector =
false;
235 if (
const CallInst *CI = dyn_cast<CallInst>(&
I))
236 if (CI->getCalledFunction() ==
238 Intrinsic::stackprotector))
241 if (F->hasFnAttribute(Attribute::SafeStack))
249 if (F->hasFnAttribute(Attribute::StackProtectReq)) {
251 <<
"Stack protection applied to function "
253 <<
" due to a function attribute or command-line switch");
254 NeedsProtector =
true;
256 }
else if (F->hasFnAttribute(Attribute::StackProtectStrong))
258 else if (HasPrologue)
259 NeedsProtector =
true;
260 else if (!F->hasFnAttribute(Attribute::StackProtect))
265 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(&
I)) {
266 if (AI->isArrayAllocation()) {
270 <<
"Stack protection applied to function "
272 <<
" due to a call to alloca or use of a variable length array";
273 if (
const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
274 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
279 NeedsProtector =
true;
284 NeedsProtector =
true;
290 NeedsProtector =
true;
295 bool IsLarge =
false;
296 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
300 <<
"Stack protection applied to function "
302 <<
" due to a stack allocated buffer or struct containing a "
304 NeedsProtector =
true;
308 if (Strong && HasAddressTaken(AI)) {
313 <<
"Stack protection applied to function "
315 <<
" due to the address of a local variable being taken");
316 NeedsProtector =
true;
322 return NeedsProtector;
329 bool *SupportsSelectionDAGSP =
nullptr) {
331 return B.
CreateLoad(Guard,
true,
"StackGuard");
344 if (SupportsSelectionDAGSP)
345 *SupportsSelectionDAGSP =
true;
362 bool SupportsSelectionDAGSP =
false;
365 AI =
B.CreateAlloca(PtrTy,
nullptr,
"StackGuardSlot");
370 return SupportsSelectionDAGSP;
379 bool StackProtector::InsertStackProtectors() {
380 bool SupportsSelectionDAGSP =
398 if (SupportsSelectionDAGSP)
413 LoadInst *Guard =
B.CreateLoad(AI,
true,
"Guard");
470 Value *Cmp =
B.CreateICmpEQ(Guard, LI2);
476 .createBranchWeights(SuccessProb.getNumerator(),
477 FailureProb.getNumerator());
478 B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
493 B.SetCurrentDebugLocation(
DebugLoc::get(0, 0, F->getSubprogram()));
500 B.CreateCall(StackChkFail,
B.CreateGlobalStringPtr(F->getName(),
"SSH"));
505 B.CreateCall(StackChkFail, {});
507 B.CreateUnreachable();
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
DiagnosticInfoOptimizationBase::Argument NV
STATISTIC(NumFunctions,"Total number of functions")
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
A Module instance is used to store all the information related to an LLVM module. ...
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
This class represents a function call, abstracting a target machine's calling convention.
const Instruction & front() const
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
An instruction for reading from memory.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI, const TargetLoweringBase *TLI, AllocaInst *&AI)
Insert code into the entry block that stores the stack guard variable onto the stack: ...
void setCallingConv(CallingConv::ID CC)
AttributeList getAttributes() const
Return the attribute list for this Function.
const Triple & getTargetTriple() const
element_iterator element_end() const
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Did not trigger a stack protector.
This class represents the LLVM 'select' instruction.
DILocation * get() const
Get the underlying DILocation.
Class to represent struct types.
static cl::opt< bool > EnableSelectionDAGSP("enable-selectiondag-sp", cl::init(true), cl::Hidden)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Constant * getPersonalityFn() const
Get the personality function associated with this function.
This file contains the simple types necessary to represent the attributes associated with functions a...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
DominatorTree & getDomTree()
element_iterator element_begin() const
The address of this allocation is exposed and triggered protection.
Target-Independent Code Generator Pass Configuration Options.
This class represents a cast from a pointer to an integer.
virtual Value * getIRStackGuard(IRBuilder<> &IRB) const
If the target has a standard location for the stack protector guard, returns the address of that loca...
Class to represent array types.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
iterator find(const KeyT &Val)
SSPLayoutKind
SSPLayoutKind.
This class represents a no-op cast from one type to another.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
An instruction for storing to memory.
Type::subtype_iterator element_iterator
Class to represent pointers.
bool runOnFunction(Function &Fn) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
LoadInst * CreateLoad(Value *Ptr, const char *Name)
initializer< Ty > init(const Ty &Val)
bool shouldEmitSDCheck(const BasicBlock &BB) const
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
virtual void insertSSPDeclarations(Module &M) const
Inserts necessary declarations for SSP (stack protection) purpose.
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool hasPersonalityFn() const
Check whether this function has a personality function.
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
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.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
void adjustForColoring(const AllocaInst *From, const AllocaInst *To)
self_iterator getIterator()
SSPLayoutKind getSSPLayout(const AllocaInst *AI) const
FunctionPass * createStackProtectorPass()
createStackProtectorPass - This pass adds stack protectors to functions.
Used in the streaming interface as the general argument type.
LLVMContext & getContext() const
All values hold a context through their type.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
virtual Value * getSSPStackGuardCheck(const Module &M) const
If the target has a standard stack protection check function that performs validation and error handl...
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (OS X, iOS, or watchOS).
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
Iterator for intrusive lists based on ilist_node.
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
Module.h This file contains the declarations for the Module class.
virtual const TargetLowering * getTargetLowering() const
const BasicBlock & getEntryBlock() const
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
iterator_range< user_iterator > users()
INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,"Insert stack protectors", false, true) INITIALIZE_PASS_END(StackProtector
CallInst * CreateCall(Value *Callee, ArrayRef< Value * > Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
bool isStringAttribute() const
Return true if the attribute is a string (target-dependent) attribute.
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
StringRef getValueAsString() const
Return the attribute's value as a string.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
Legacy analysis pass which computes a DominatorTree.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
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.
static BranchProbability getBranchProbStackProtector(bool IsLikely)
Array or nested array >= SSP-buffer-size.
bool erase(const KeyT &Val)
Array or nested array < SSP-buffer-size.
This file describes how to lower LLVM code to machine code.
an instruction to allocate memory on the stack