StackProtector.cpp [plain text]
#define DEBUG_TYPE "stack-protector"
#include "llvm/CodeGen/StackProtector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/CodeGen/Analysis.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include <cstdlib>
using namespace llvm;
STATISTIC(NumFunProtected, "Number of functions protected");
STATISTIC(NumAddrTaken, "Number of local variables that have their address"
" taken.");
static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
cl::init(true), cl::Hidden);
char StackProtector::ID = 0;
INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors",
false, true)
FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
return new StackProtector(TM);
}
StackProtector::SSPLayoutKind
StackProtector::getSSPLayout(const AllocaInst *AI) const {
return AI ? Layout.lookup(AI) : SSPLK_None;
}
void StackProtector::adjustForColoring(const AllocaInst *From,
const AllocaInst *To) {
SSPLayoutMap::iterator I = Layout.find(From);
if (I != Layout.end()) {
SSPLayoutKind Kind = I->second;
Layout.erase(I);
I = Layout.find(To);
if (I == Layout.end())
Layout.insert(std::make_pair(To, Kind));
else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
I->second = Kind;
}
}
bool StackProtector::runOnFunction(Function &Fn) {
F = &Fn;
M = F->getParent();
DominatorTreeWrapperPass *DTWP =
getAnalysisIfAvailable<DominatorTreeWrapperPass>();
DT = DTWP ? &DTWP->getDomTree() : 0;
TLI = TM->getTargetLowering();
if (!RequiresStackProtector())
return false;
Attribute Attr = Fn.getAttributes().getAttribute(
AttributeSet::FunctionIndex, "stack-protector-buffer-size");
if (Attr.isStringAttribute() &&
Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
return false;
++NumFunProtected;
return InsertStackProtectors();
}
bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
bool Strong,
bool InStruct) const {
if (!Ty)
return false;
if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
if (!AT->getElementType()->isIntegerTy(8)) {
if (!Strong && (InStruct || !Trip.isOSDarwin()))
return false;
}
if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT)) {
IsLarge = true;
return true;
}
if (Strong)
return true;
}
const StructType *ST = dyn_cast<StructType>(Ty);
if (!ST)
return false;
bool NeedsProtector = false;
for (StructType::element_iterator I = ST->element_begin(),
E = ST->element_end();
I != E; ++I)
if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
if (IsLarge)
return true;
NeedsProtector = true;
}
return NeedsProtector;
}
bool StackProtector::HasAddressTaken(const Instruction *AI) {
for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
UI != UE; ++UI) {
const User *U = *UI;
if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
if (AI == SI->getValueOperand())
return true;
} else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
if (AI == SI->getOperand(0))
return true;
} else if (isa<CallInst>(U)) {
return true;
} else if (isa<InvokeInst>(U)) {
return true;
} else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
if (HasAddressTaken(SI))
return true;
} else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
if (VisitedPHIs.insert(PN))
if (HasAddressTaken(PN))
return true;
} else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
if (HasAddressTaken(GEP))
return true;
} else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
if (HasAddressTaken(BI))
return true;
}
}
return false;
}
bool StackProtector::RequiresStackProtector() {
bool Strong = false;
bool NeedsProtector = false;
if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
Attribute::StackProtectReq)) {
NeedsProtector = true;
Strong = true; } else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
Attribute::StackProtectStrong))
Strong = true;
else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
Attribute::StackProtect))
return false;
for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
BasicBlock *BB = I;
for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
++II) {
if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
if (AI->isArrayAllocation()) {
if (Strong)
return true;
if (const ConstantInt *CI =
dyn_cast<ConstantInt>(AI->getArraySize())) {
if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
NeedsProtector = true;
} else if (Strong) {
Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
NeedsProtector = true;
}
} else {
Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
NeedsProtector = true;
}
continue;
}
bool IsLarge = false;
if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
: SSPLK_SmallArray));
NeedsProtector = true;
continue;
}
if (Strong && HasAddressTaken(AI)) {
++NumAddrTaken;
Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
NeedsProtector = true;
}
}
}
}
return NeedsProtector;
}
static bool InstructionWillNotHaveChain(const Instruction *I) {
return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
isSafeToSpeculativelyExecute(I);
}
static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI,
const TargetLoweringBase *TLI) {
unsigned SearchCounter = 0;
const unsigned MaxSearch = 4;
bool NoInterposingChain = true;
for (BasicBlock::reverse_iterator I = llvm::next(BB->rbegin()),
E = BB->rend();
I != E && SearchCounter < MaxSearch; ++I) {
Instruction *Inst = &*I;
if (isa<DbgInfoIntrinsic>(Inst))
continue;
if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
if (CI->isTailCall() &&
(InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
return CI;
}
NoInterposingChain =
NoInterposingChain && InstructionWillNotHaveChain(Inst);
SearchCounter++;
}
return 0;
}
static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
const TargetLoweringBase *TLI, const Triple &Trip,
AllocaInst *&AI, Value *&StackGuardVar) {
bool SupportsSelectionDAGSP = false;
PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
unsigned AddressSpace, Offset;
if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
Constant *OffsetVal =
ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
StackGuardVar = ConstantExpr::getIntToPtr(
OffsetVal, PointerType::get(PtrTy, AddressSpace));
} else if (Trip.getOS() == llvm::Triple::OpenBSD) {
StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
cast<GlobalValue>(StackGuardVar)
->setVisibility(GlobalValue::HiddenVisibility);
} else {
SupportsSelectionDAGSP = true;
StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
}
IRBuilder<> B(&F->getEntryBlock().front());
AI = B.CreateAlloca(PtrTy, 0, "StackGuardSlot");
LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
B.CreateCall2(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), LI,
AI);
return SupportsSelectionDAGSP;
}
bool StackProtector::InsertStackProtectors() {
bool HasPrologue = false;
bool SupportsSelectionDAGSP =
EnableSelectionDAGSP && !TM->Options.EnableFastISel;
AllocaInst *AI = 0; Value *StackGuardVar = 0;
for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
BasicBlock *BB = I++;
ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
if (!RI)
continue;
if (!HasPrologue) {
HasPrologue = true;
SupportsSelectionDAGSP &=
CreatePrologue(F, M, RI, TLI, Trip, AI, StackGuardVar);
}
if (SupportsSelectionDAGSP) {
Instruction *InsertionPt = 0;
if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
InsertionPt = CI;
} else {
InsertionPt = RI;
assert(InsertionPt != 0 && "BB must have a terminator instruction at "
"this point.");
}
Function *Intrinsic =
Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt);
} else {
BasicBlock *FailBB = CreateFailBB();
BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
if (DT && DT->isReachableFromEntry(BB)) {
DT->addNewBlock(NewBB, BB);
DT->addNewBlock(FailBB, BB);
}
BB->getTerminator()->eraseFromParent();
NewBB->moveAfter(BB);
IRBuilder<> B(BB);
LoadInst *LI1 = B.CreateLoad(StackGuardVar);
LoadInst *LI2 = B.CreateLoad(AI);
Value *Cmp = B.CreateICmpEQ(LI1, LI2);
B.CreateCondBr(Cmp, NewBB, FailBB);
}
}
if (!HasPrologue)
return false;
return true;
}
BasicBlock *StackProtector::CreateFailBB() {
LLVMContext &Context = F->getContext();
BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
IRBuilder<> B(FailBB);
if (Trip.getOS() == llvm::Triple::OpenBSD) {
Constant *StackChkFail = M->getOrInsertFunction(
"__stack_smash_handler", Type::getVoidTy(Context),
Type::getInt8PtrTy(Context), NULL);
B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
} else {
Constant *StackChkFail = M->getOrInsertFunction(
"__stack_chk_fail", Type::getVoidTy(Context), NULL);
B.CreateCall(StackChkFail);
}
B.CreateUnreachable();
return FailBB;
}