StackProtector.cpp [plain text]
#define DEBUG_TYPE "stack-protector"
#include "llvm/CodeGen/Passes.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/Dominators.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/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/TargetOptions.h"
using namespace llvm;
STATISTIC(NumFunProtected, "Number of functions protected");
STATISTIC(NumAddrTaken, "Number of local variables that have their address"
" taken.");
namespace {
class StackProtector : public FunctionPass {
const TargetLoweringBase *TLI;
Function *F;
Module *M;
DominatorTree *DT;
SmallPtrSet<const PHINode*, 16> VisitedPHIs;
bool InsertStackProtectors();
BasicBlock *CreateFailBB();
bool ContainsProtectableArray(Type *Ty, bool Strong = false,
bool InStruct = false) const;
bool HasAddressTaken(const Instruction *AI);
bool RequiresStackProtector();
public:
static char ID; StackProtector() : FunctionPass(ID), TLI(0) {
initializeStackProtectorPass(*PassRegistry::getPassRegistry());
}
StackProtector(const TargetLoweringBase *tli)
: FunctionPass(ID), TLI(tli) {
initializeStackProtectorPass(*PassRegistry::getPassRegistry());
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addPreserved<DominatorTree>();
}
virtual bool runOnFunction(Function &Fn);
};
}
char StackProtector::ID = 0;
INITIALIZE_PASS(StackProtector, "stack-protector",
"Insert stack protectors", false, false)
FunctionPass *llvm::createStackProtectorPass(const TargetLoweringBase *tli) {
return new StackProtector(tli);
}
bool StackProtector::runOnFunction(Function &Fn) {
F = &Fn;
M = F->getParent();
DT = getAnalysisIfAvailable<DominatorTree>();
if (!RequiresStackProtector()) return false;
++NumFunProtected;
return InsertStackProtectors();
}
bool StackProtector::ContainsProtectableArray(Type *Ty, bool Strong,
bool InStruct) const {
if (!Ty) return false;
if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
if (Strong)
return true;
const TargetMachine &TM = TLI->getTargetMachine();
if (!AT->getElementType()->isIntegerTy(8)) {
Triple Trip(TM.getTargetTriple());
if (InStruct || !Trip.isOSDarwin())
return false;
}
if (TM.Options.SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT))
return true;
}
const StructType *ST = dyn_cast<StructType>(Ty);
if (!ST) return false;
for (StructType::element_iterator I = ST->element_begin(),
E = ST->element_end(); I != E; ++I)
if (ContainsProtectableArray(*I, Strong, true))
return true;
return false;
}
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;
if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
Attribute::StackProtectReq))
return 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())) {
unsigned BufferSize = TLI->getTargetMachine().Options.SSPBufferSize;
if (CI->getLimitedValue(BufferSize) >= BufferSize)
return true;
} else return true;
}
if (ContainsProtectableArray(AI->getAllocatedType(), Strong))
return true;
if (Strong && HasAddressTaken(AI)) {
++NumAddrTaken;
return true;
}
}
}
}
return false;
}
bool StackProtector::InsertStackProtectors() {
BasicBlock *FailBB = 0; BasicBlock *FailBBDom = 0; 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 (!FailBB) {
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 {
StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
}
BasicBlock &Entry = F->getEntryBlock();
Instruction *InsPt = &Entry.front();
AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
Value *Args[] = { LI, AI };
CallInst::
Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
Args, "", InsPt);
FailBB = CreateFailBB();
}
BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
if (DT && DT->isReachableFromEntry(BB)) {
DT->addNewBlock(NewBB, BB);
FailBBDom = FailBBDom ? DT->findNearestCommonDominator(FailBBDom, BB) :BB;
}
BB->getTerminator()->eraseFromParent();
NewBB->moveAfter(BB);
LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
LoadInst *LI2 = new LoadInst(AI, "", true, BB);
ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
BranchInst::Create(NewBB, FailBB, Cmp, BB);
}
if (!FailBB) return false;
if (DT && FailBBDom)
DT->addNewBlock(FailBB, FailBBDom);
return true;
}
BasicBlock *StackProtector::CreateFailBB() {
BasicBlock *FailBB = BasicBlock::Create(F->getContext(),
"CallStackCheckFailBlk", F);
Constant *StackChkFail =
M->getOrInsertFunction("__stack_chk_fail",
Type::getVoidTy(F->getContext()), NULL);
CallInst::Create(StackChkFail, "", FailBB);
new UnreachableInst(F->getContext(), FailBB);
return FailBB;
}