#include "llvm/CodeGen/StackProtector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/BranchProbabilityInfo.h"
#include "llvm/Analysis/EHPersonalities.h"
#include "llvm/Analysis/MemoryLocation.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/User.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include <utility>
using namespace llvm;
#define DEBUG_TYPE "stack-protector"
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;
StackProtector::StackProtector() : FunctionPass(ID), SSPBufferSize(8) {
initializeStackProtectorPass(*PassRegistry::getPassRegistry());
}
INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
"Insert stack protectors", false, true)
INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
"Insert stack protectors", false, true)
FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetPassConfig>();
AU.addPreserved<DominatorTreeWrapperPass>();
}
bool StackProtector::runOnFunction(Function &Fn) {
F = &Fn;
M = F->getParent();
DominatorTreeWrapperPass *DTWP =
getAnalysisIfAvailable<DominatorTreeWrapperPass>();
DT = DTWP ? &DTWP->getDomTree() : nullptr;
TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
Trip = TM->getTargetTriple();
TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
HasPrologue = false;
HasIRCheck = false;
Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
if (Attr.isStringAttribute() &&
Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
return false;
if (!RequiresStackProtector())
return false;
if (Fn.hasPersonalityFn()) {
EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
if (isFuncletEHPersonality(Personality))
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 <= M->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 (Type *ET : ST->elements())
if (ContainsProtectableArray(ET, IsLarge, Strong, true)) {
if (IsLarge)
return true;
NeedsProtector = true;
}
return NeedsProtector;
}
bool StackProtector::HasAddressTaken(const Instruction *AI,
TypeSize AllocSize) {
const DataLayout &DL = M->getDataLayout();
for (const User *U : AI->users()) {
const auto *I = cast<Instruction>(U);
Optional<MemoryLocation> MemLoc = MemoryLocation::getOrNone(I);
if (MemLoc && MemLoc->Size.hasValue() &&
!TypeSize::isKnownGE(AllocSize,
TypeSize::getFixed(MemLoc->Size.getValue())))
return true;
switch (I->getOpcode()) {
case Instruction::Store:
if (AI == cast<StoreInst>(I)->getValueOperand())
return true;
break;
case Instruction::AtomicCmpXchg:
if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand())
return true;
break;
case Instruction::PtrToInt:
if (AI == cast<PtrToIntInst>(I)->getOperand(0))
return true;
break;
case Instruction::Call: {
const auto *CI = cast<CallInst>(I);
if (!CI->isDebugOrPseudoInst() && !CI->isLifetimeStartOrEnd())
return true;
break;
}
case Instruction::Invoke:
return true;
case Instruction::GetElementPtr: {
const GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
unsigned IndexSize = DL.getIndexTypeSizeInBits(I->getType());
APInt Offset(IndexSize, 0);
if (!GEP->accumulateConstantOffset(DL, Offset))
return true;
TypeSize OffsetSize = TypeSize::Fixed(Offset.getLimitedValue());
if (!TypeSize::isKnownGT(AllocSize, OffsetSize))
return true;
TypeSize NewAllocSize =
TypeSize::Fixed(AllocSize.getKnownMinValue()) - OffsetSize;
if (HasAddressTaken(I, NewAllocSize))
return true;
break;
}
case Instruction::BitCast:
case Instruction::Select:
case Instruction::AddrSpaceCast:
if (HasAddressTaken(I, AllocSize))
return true;
break;
case Instruction::PHI: {
const auto *PN = cast<PHINode>(I);
if (VisitedPHIs.insert(PN).second)
if (HasAddressTaken(PN, AllocSize))
return true;
break;
}
case Instruction::Load:
case Instruction::AtomicRMW:
case Instruction::Ret:
break;
default:
return true;
}
}
return false;
}
static const CallInst *findStackProtectorIntrinsic(Function &F) {
for (const BasicBlock &BB : F)
for (const Instruction &I : BB)
if (const auto *II = dyn_cast<IntrinsicInst>(&I))
if (II->getIntrinsicID() == Intrinsic::stackprotector)
return II;
return nullptr;
}
bool StackProtector::RequiresStackProtector() {
bool Strong = false;
bool NeedsProtector = false;
if (F->hasFnAttribute(Attribute::SafeStack))
return false;
OptimizationRemarkEmitter ORE(F);
if (F->hasFnAttribute(Attribute::StackProtectReq)) {
ORE.emit([&]() {
return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
<< "Stack protection applied to function "
<< ore::NV("Function", F)
<< " due to a function attribute or command-line switch";
});
NeedsProtector = true;
Strong = true; } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
Strong = true;
else if (!F->hasFnAttribute(Attribute::StackProtect))
return false;
for (const BasicBlock &BB : *F) {
for (const Instruction &I : BB) {
if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
if (AI->isArrayAllocation()) {
auto RemarkBuilder = [&]() {
return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
&I)
<< "Stack protection applied to function "
<< ore::NV("Function", F)
<< " due to a call to alloca or use of a variable length "
"array";
};
if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
Layout.insert(std::make_pair(AI,
MachineFrameInfo::SSPLK_LargeArray));
ORE.emit(RemarkBuilder);
NeedsProtector = true;
} else if (Strong) {
Layout.insert(std::make_pair(AI,
MachineFrameInfo::SSPLK_SmallArray));
ORE.emit(RemarkBuilder);
NeedsProtector = true;
}
} else {
Layout.insert(std::make_pair(AI,
MachineFrameInfo::SSPLK_LargeArray));
ORE.emit(RemarkBuilder);
NeedsProtector = true;
}
continue;
}
bool IsLarge = false;
if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
Layout.insert(std::make_pair(AI, IsLarge
? MachineFrameInfo::SSPLK_LargeArray
: MachineFrameInfo::SSPLK_SmallArray));
ORE.emit([&]() {
return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
<< "Stack protection applied to function "
<< ore::NV("Function", F)
<< " due to a stack allocated buffer or struct containing a "
"buffer";
});
NeedsProtector = true;
continue;
}
if (Strong && HasAddressTaken(AI, M->getDataLayout().getTypeAllocSize(
AI->getAllocatedType()))) {
++NumAddrTaken;
Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
ORE.emit([&]() {
return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
&I)
<< "Stack protection applied to function "
<< ore::NV("Function", F)
<< " due to the address of a local variable being taken";
});
NeedsProtector = true;
}
VisitedPHIs.clear();
}
}
}
return NeedsProtector;
}
static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
IRBuilder<> &B,
bool *SupportsSelectionDAGSP = nullptr) {
Value *Guard = TLI->getIRStackGuard(B);
StringRef GuardMode = M->getStackProtectorGuard();
if ((GuardMode == "tls" || GuardMode.empty()) && Guard)
return B.CreateLoad(B.getInt8PtrTy(), Guard, true, "StackGuard");
if (SupportsSelectionDAGSP)
*SupportsSelectionDAGSP = true;
TLI->insertSSPDeclarations(*M);
return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
}
static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
const TargetLoweringBase *TLI, AllocaInst *&AI) {
bool SupportsSelectionDAGSP = false;
IRBuilder<> B(&F->getEntryBlock().front());
PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
{GuardSlot, AI});
return SupportsSelectionDAGSP;
}
bool StackProtector::InsertStackProtectors() {
bool SupportsSelectionDAGSP =
TLI->useStackGuardXorFP() ||
(EnableSelectionDAGSP && !TM->Options.EnableFastISel);
AllocaInst *AI = nullptr;
for (BasicBlock &BB : llvm::make_early_inc_range(*F)) {
ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator());
if (!RI)
continue;
if (!HasPrologue) {
HasPrologue = true;
SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
}
if (SupportsSelectionDAGSP)
break;
if (!AI) {
const CallInst *SPCall = findStackProtectorIntrinsic(*F);
assert(SPCall && "Call to llvm.stackprotector is missing");
AI = cast<AllocaInst>(SPCall->getArgOperand(1));
}
HasIRCheck = true;
Instruction *CheckLoc = RI;
Instruction *Prev = RI->getPrevNonDebugInstruction();
if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isMustTailCall())
CheckLoc = Prev;
else if (Prev) {
Prev = Prev->getPrevNonDebugInstruction();
if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isMustTailCall())
CheckLoc = Prev;
}
if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
IRBuilder<> B(CheckLoc);
LoadInst *Guard = B.CreateLoad(B.getInt8PtrTy(), AI, true, "Guard");
CallInst *Call = B.CreateCall(GuardCheck, {Guard});
Call->setAttributes(GuardCheck->getAttributes());
Call->setCallingConv(GuardCheck->getCallingConv());
} else {
BasicBlock *FailBB = CreateFailBB();
BasicBlock *NewBB =
BB.splitBasicBlock(CheckLoc->getIterator(), "SP_return");
if (DT && DT->isReachableFromEntry(&BB)) {
DT->addNewBlock(NewBB, &BB);
DT->addNewBlock(FailBB, &BB);
}
BB.getTerminator()->eraseFromParent();
NewBB->moveAfter(&BB);
IRBuilder<> B(&BB);
Value *Guard = getStackGuard(TLI, M, B);
LoadInst *LI2 = B.CreateLoad(B.getInt8PtrTy(), AI, true);
Value *Cmp = B.CreateICmpEQ(Guard, LI2);
auto SuccessProb =
BranchProbabilityInfo::getBranchProbStackProtector(true);
auto FailureProb =
BranchProbabilityInfo::getBranchProbStackProtector(false);
MDNode *Weights = MDBuilder(F->getContext())
.createBranchWeights(SuccessProb.getNumerator(),
FailureProb.getNumerator());
B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
}
}
return HasPrologue;
}
BasicBlock *StackProtector::CreateFailBB() {
LLVMContext &Context = F->getContext();
BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
IRBuilder<> B(FailBB);
if (F->getSubprogram())
B.SetCurrentDebugLocation(
DILocation::get(Context, 0, 0, F->getSubprogram()));
if (Trip.isOSOpenBSD()) {
FunctionCallee StackChkFail = M->getOrInsertFunction(
"__stack_smash_handler", Type::getVoidTy(Context),
Type::getInt8PtrTy(Context));
B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
} else {
FunctionCallee StackChkFail =
M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
B.CreateCall(StackChkFail, {});
}
B.CreateUnreachable();
return FailBB;
}
bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator());
}
void StackProtector::copyToMachineFrameInfo(MachineFrameInfo &MFI) const {
if (Layout.empty())
return;
for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
if (MFI.isDeadObjectIndex(I))
continue;
const AllocaInst *AI = MFI.getObjectAllocation(I);
if (!AI)
continue;
SSPLayoutMap::const_iterator LI = Layout.find(AI);
if (LI == Layout.end())
continue;
MFI.setObjectSSPLayout(I, LI->second);
}
}