109467b48Spatrick //===- StackProtector.cpp - Stack Protector Insertion ---------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This pass inserts stack protectors into functions which need them. A variable
1009467b48Spatrick // with a random value in it is stored onto the stack before the local variables
1109467b48Spatrick // are allocated. Upon exiting the block, the stored value is checked. If it's
1209467b48Spatrick // changed, then there was some sort of violation and the program aborts.
1309467b48Spatrick //
1409467b48Spatrick //===----------------------------------------------------------------------===//
1509467b48Spatrick
1609467b48Spatrick #include "llvm/CodeGen/StackProtector.h"
1709467b48Spatrick #include "llvm/ADT/SmallPtrSet.h"
1809467b48Spatrick #include "llvm/ADT/Statistic.h"
1909467b48Spatrick #include "llvm/Analysis/BranchProbabilityInfo.h"
2009467b48Spatrick #include "llvm/Analysis/EHPersonalities.h"
21097a140dSpatrick #include "llvm/Analysis/MemoryLocation.h"
2209467b48Spatrick #include "llvm/Analysis/OptimizationRemarkEmitter.h"
2309467b48Spatrick #include "llvm/CodeGen/Passes.h"
2409467b48Spatrick #include "llvm/CodeGen/TargetLowering.h"
2509467b48Spatrick #include "llvm/CodeGen/TargetPassConfig.h"
2609467b48Spatrick #include "llvm/CodeGen/TargetSubtargetInfo.h"
2709467b48Spatrick #include "llvm/IR/Attributes.h"
2809467b48Spatrick #include "llvm/IR/BasicBlock.h"
2909467b48Spatrick #include "llvm/IR/Constants.h"
3009467b48Spatrick #include "llvm/IR/DataLayout.h"
3109467b48Spatrick #include "llvm/IR/DerivedTypes.h"
3209467b48Spatrick #include "llvm/IR/Dominators.h"
3309467b48Spatrick #include "llvm/IR/Function.h"
3409467b48Spatrick #include "llvm/IR/IRBuilder.h"
3509467b48Spatrick #include "llvm/IR/Instruction.h"
3609467b48Spatrick #include "llvm/IR/Instructions.h"
3709467b48Spatrick #include "llvm/IR/IntrinsicInst.h"
3809467b48Spatrick #include "llvm/IR/Intrinsics.h"
3909467b48Spatrick #include "llvm/IR/MDBuilder.h"
4009467b48Spatrick #include "llvm/IR/Module.h"
4109467b48Spatrick #include "llvm/IR/Type.h"
4209467b48Spatrick #include "llvm/IR/User.h"
4309467b48Spatrick #include "llvm/InitializePasses.h"
4409467b48Spatrick #include "llvm/Pass.h"
4509467b48Spatrick #include "llvm/Support/Casting.h"
4609467b48Spatrick #include "llvm/Support/CommandLine.h"
4709467b48Spatrick #include "llvm/Target/TargetMachine.h"
4809467b48Spatrick #include "llvm/Target/TargetOptions.h"
49*d415bd75Srobert #include "llvm/Transforms/Utils/BasicBlockUtils.h"
50*d415bd75Srobert #include <optional>
5109467b48Spatrick #include <utility>
5209467b48Spatrick
5309467b48Spatrick using namespace llvm;
5409467b48Spatrick
5509467b48Spatrick #define DEBUG_TYPE "stack-protector"
5609467b48Spatrick
5709467b48Spatrick STATISTIC(NumFunProtected, "Number of functions protected");
5809467b48Spatrick STATISTIC(NumAddrTaken, "Number of local variables that have their address"
5909467b48Spatrick " taken.");
6009467b48Spatrick
6109467b48Spatrick static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
6209467b48Spatrick cl::init(true), cl::Hidden);
63*d415bd75Srobert static cl::opt<bool> DisableCheckNoReturn("disable-check-noreturn-call",
64*d415bd75Srobert cl::init(false), cl::Hidden);
6509467b48Spatrick
6609467b48Spatrick char StackProtector::ID = 0;
6709467b48Spatrick
StackProtector()68*d415bd75Srobert StackProtector::StackProtector() : FunctionPass(ID) {
6909467b48Spatrick initializeStackProtectorPass(*PassRegistry::getPassRegistry());
7009467b48Spatrick }
7109467b48Spatrick
7209467b48Spatrick INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
7309467b48Spatrick "Insert stack protectors", false, true)
INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)7409467b48Spatrick INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
7573471bf0Spatrick INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7609467b48Spatrick INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
7709467b48Spatrick "Insert stack protectors", false, true)
7809467b48Spatrick
7909467b48Spatrick FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
8009467b48Spatrick
getAnalysisUsage(AnalysisUsage & AU) const8109467b48Spatrick void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
8209467b48Spatrick AU.addRequired<TargetPassConfig>();
8309467b48Spatrick AU.addPreserved<DominatorTreeWrapperPass>();
8409467b48Spatrick }
8509467b48Spatrick
runOnFunction(Function & Fn)8609467b48Spatrick bool StackProtector::runOnFunction(Function &Fn) {
8709467b48Spatrick F = &Fn;
8809467b48Spatrick M = F->getParent();
89*d415bd75Srobert if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
90*d415bd75Srobert DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
9109467b48Spatrick TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
9209467b48Spatrick Trip = TM->getTargetTriple();
9309467b48Spatrick TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
9409467b48Spatrick HasPrologue = false;
9509467b48Spatrick HasIRCheck = false;
9609467b48Spatrick
97*d415bd75Srobert SSPBufferSize = Fn.getFnAttributeAsParsedInteger(
98*d415bd75Srobert "stack-protector-buffer-size", DefaultSSPBufferSize);
9909467b48Spatrick if (!RequiresStackProtector())
10009467b48Spatrick return false;
10109467b48Spatrick
10209467b48Spatrick // TODO(etienneb): Functions with funclets are not correctly supported now.
10309467b48Spatrick // Do nothing if this is funclet-based personality.
10409467b48Spatrick if (Fn.hasPersonalityFn()) {
10509467b48Spatrick EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
10609467b48Spatrick if (isFuncletEHPersonality(Personality))
10709467b48Spatrick return false;
10809467b48Spatrick }
10909467b48Spatrick
11009467b48Spatrick ++NumFunProtected;
111*d415bd75Srobert bool Changed = InsertStackProtectors();
112*d415bd75Srobert #ifdef EXPENSIVE_CHECKS
113*d415bd75Srobert assert((!DTU ||
114*d415bd75Srobert DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full)) &&
115*d415bd75Srobert "Failed to maintain validity of domtree!");
116*d415bd75Srobert #endif
117*d415bd75Srobert DTU.reset();
118*d415bd75Srobert return Changed;
11909467b48Spatrick }
12009467b48Spatrick
12109467b48Spatrick /// \param [out] IsLarge is set to true if a protectable array is found and
12209467b48Spatrick /// it is "large" ( >= ssp-buffer-size). In the case of a structure with
12309467b48Spatrick /// multiple arrays, this gets set if any of them is large.
ContainsProtectableArray(Type * Ty,bool & IsLarge,bool Strong,bool InStruct) const12409467b48Spatrick bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
12509467b48Spatrick bool Strong,
12609467b48Spatrick bool InStruct) const {
12709467b48Spatrick if (!Ty)
12809467b48Spatrick return false;
12909467b48Spatrick if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
13009467b48Spatrick if (!AT->getElementType()->isIntegerTy(8)) {
13109467b48Spatrick // If we're on a non-Darwin platform or we're inside of a structure, don't
13209467b48Spatrick // add stack protectors unless the array is a character array.
13309467b48Spatrick // However, in strong mode any array, regardless of type and size,
13409467b48Spatrick // triggers a protector.
13509467b48Spatrick if (!Strong && (InStruct || !Trip.isOSDarwin()))
13609467b48Spatrick return false;
13709467b48Spatrick }
13809467b48Spatrick
13909467b48Spatrick // If an array has more than SSPBufferSize bytes of allocated space, then we
14009467b48Spatrick // emit stack protectors.
14109467b48Spatrick if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
14209467b48Spatrick IsLarge = true;
14309467b48Spatrick return true;
14409467b48Spatrick }
14509467b48Spatrick
14609467b48Spatrick if (Strong)
14709467b48Spatrick // Require a protector for all arrays in strong mode
14809467b48Spatrick return true;
14909467b48Spatrick }
15009467b48Spatrick
15109467b48Spatrick const StructType *ST = dyn_cast<StructType>(Ty);
15209467b48Spatrick if (!ST)
15309467b48Spatrick return false;
15409467b48Spatrick
15509467b48Spatrick bool NeedsProtector = false;
156*d415bd75Srobert for (Type *ET : ST->elements())
157*d415bd75Srobert if (ContainsProtectableArray(ET, IsLarge, Strong, true)) {
15809467b48Spatrick // If the element is a protectable array and is large (>= SSPBufferSize)
15909467b48Spatrick // then we are done. If the protectable array is not large, then
16009467b48Spatrick // keep looking in case a subsequent element is a large array.
16109467b48Spatrick if (IsLarge)
16209467b48Spatrick return true;
16309467b48Spatrick NeedsProtector = true;
16409467b48Spatrick }
16509467b48Spatrick
16609467b48Spatrick return NeedsProtector;
16709467b48Spatrick }
16809467b48Spatrick
HasAddressTaken(const Instruction * AI,TypeSize AllocSize)169097a140dSpatrick bool StackProtector::HasAddressTaken(const Instruction *AI,
170*d415bd75Srobert TypeSize AllocSize) {
171097a140dSpatrick const DataLayout &DL = M->getDataLayout();
17209467b48Spatrick for (const User *U : AI->users()) {
17309467b48Spatrick const auto *I = cast<Instruction>(U);
174097a140dSpatrick // If this instruction accesses memory make sure it doesn't access beyond
175097a140dSpatrick // the bounds of the allocated object.
176*d415bd75Srobert std::optional<MemoryLocation> MemLoc = MemoryLocation::getOrNone(I);
177*d415bd75Srobert if (MemLoc && MemLoc->Size.hasValue() &&
178*d415bd75Srobert !TypeSize::isKnownGE(AllocSize,
179*d415bd75Srobert TypeSize::getFixed(MemLoc->Size.getValue())))
180097a140dSpatrick return true;
18109467b48Spatrick switch (I->getOpcode()) {
18209467b48Spatrick case Instruction::Store:
18309467b48Spatrick if (AI == cast<StoreInst>(I)->getValueOperand())
18409467b48Spatrick return true;
18509467b48Spatrick break;
18609467b48Spatrick case Instruction::AtomicCmpXchg:
18709467b48Spatrick // cmpxchg conceptually includes both a load and store from the same
18809467b48Spatrick // location. So, like store, the value being stored is what matters.
18909467b48Spatrick if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand())
19009467b48Spatrick return true;
19109467b48Spatrick break;
19209467b48Spatrick case Instruction::PtrToInt:
19309467b48Spatrick if (AI == cast<PtrToIntInst>(I)->getOperand(0))
19409467b48Spatrick return true;
19509467b48Spatrick break;
19609467b48Spatrick case Instruction::Call: {
19709467b48Spatrick // Ignore intrinsics that do not become real instructions.
19809467b48Spatrick // TODO: Narrow this to intrinsics that have store-like effects.
19909467b48Spatrick const auto *CI = cast<CallInst>(I);
20073471bf0Spatrick if (!CI->isDebugOrPseudoInst() && !CI->isLifetimeStartOrEnd())
20109467b48Spatrick return true;
20209467b48Spatrick break;
20309467b48Spatrick }
20409467b48Spatrick case Instruction::Invoke:
20509467b48Spatrick return true;
206097a140dSpatrick case Instruction::GetElementPtr: {
207097a140dSpatrick // If the GEP offset is out-of-bounds, or is non-constant and so has to be
208097a140dSpatrick // assumed to be potentially out-of-bounds, then any memory access that
209097a140dSpatrick // would use it could also be out-of-bounds meaning stack protection is
210097a140dSpatrick // required.
211097a140dSpatrick const GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
212*d415bd75Srobert unsigned IndexSize = DL.getIndexTypeSizeInBits(I->getType());
213*d415bd75Srobert APInt Offset(IndexSize, 0);
214*d415bd75Srobert if (!GEP->accumulateConstantOffset(DL, Offset))
215*d415bd75Srobert return true;
216*d415bd75Srobert TypeSize OffsetSize = TypeSize::Fixed(Offset.getLimitedValue());
217*d415bd75Srobert if (!TypeSize::isKnownGT(AllocSize, OffsetSize))
218097a140dSpatrick return true;
219097a140dSpatrick // Adjust AllocSize to be the space remaining after this offset.
220*d415bd75Srobert // We can't subtract a fixed size from a scalable one, so in that case
221*d415bd75Srobert // assume the scalable value is of minimum size.
222*d415bd75Srobert TypeSize NewAllocSize =
223*d415bd75Srobert TypeSize::Fixed(AllocSize.getKnownMinValue()) - OffsetSize;
224*d415bd75Srobert if (HasAddressTaken(I, NewAllocSize))
225097a140dSpatrick return true;
226097a140dSpatrick break;
227097a140dSpatrick }
22809467b48Spatrick case Instruction::BitCast:
22909467b48Spatrick case Instruction::Select:
23009467b48Spatrick case Instruction::AddrSpaceCast:
231097a140dSpatrick if (HasAddressTaken(I, AllocSize))
23209467b48Spatrick return true;
23309467b48Spatrick break;
23409467b48Spatrick case Instruction::PHI: {
23509467b48Spatrick // Keep track of what PHI nodes we have already visited to ensure
23609467b48Spatrick // they are only visited once.
23709467b48Spatrick const auto *PN = cast<PHINode>(I);
23809467b48Spatrick if (VisitedPHIs.insert(PN).second)
239097a140dSpatrick if (HasAddressTaken(PN, AllocSize))
24009467b48Spatrick return true;
24109467b48Spatrick break;
24209467b48Spatrick }
24309467b48Spatrick case Instruction::Load:
24409467b48Spatrick case Instruction::AtomicRMW:
24509467b48Spatrick case Instruction::Ret:
24609467b48Spatrick // These instructions take an address operand, but have load-like or
24709467b48Spatrick // other innocuous behavior that should not trigger a stack protector.
24809467b48Spatrick // atomicrmw conceptually has both load and store semantics, but the
24909467b48Spatrick // value being stored must be integer; so if a pointer is being stored,
25009467b48Spatrick // we'll catch it in the PtrToInt case above.
25109467b48Spatrick break;
25209467b48Spatrick default:
25309467b48Spatrick // Conservatively return true for any instruction that takes an address
25409467b48Spatrick // operand, but is not handled above.
25509467b48Spatrick return true;
25609467b48Spatrick }
25709467b48Spatrick }
25809467b48Spatrick return false;
25909467b48Spatrick }
26009467b48Spatrick
26109467b48Spatrick /// Search for the first call to the llvm.stackprotector intrinsic and return it
26209467b48Spatrick /// if present.
findStackProtectorIntrinsic(Function & F)26309467b48Spatrick static const CallInst *findStackProtectorIntrinsic(Function &F) {
26409467b48Spatrick for (const BasicBlock &BB : F)
26509467b48Spatrick for (const Instruction &I : BB)
26673471bf0Spatrick if (const auto *II = dyn_cast<IntrinsicInst>(&I))
26773471bf0Spatrick if (II->getIntrinsicID() == Intrinsic::stackprotector)
26873471bf0Spatrick return II;
26909467b48Spatrick return nullptr;
27009467b48Spatrick }
27109467b48Spatrick
27209467b48Spatrick /// Check whether or not this function needs a stack protector based
27309467b48Spatrick /// upon the stack protector level.
27409467b48Spatrick ///
27509467b48Spatrick /// We use two heuristics: a standard (ssp) and strong (sspstrong).
27609467b48Spatrick /// The standard heuristic which will add a guard variable to functions that
27709467b48Spatrick /// call alloca with a either a variable size or a size >= SSPBufferSize,
27809467b48Spatrick /// functions with character buffers larger than SSPBufferSize, and functions
27909467b48Spatrick /// with aggregates containing character buffers larger than SSPBufferSize. The
28009467b48Spatrick /// strong heuristic will add a guard variables to functions that call alloca
28109467b48Spatrick /// regardless of size, functions with any buffer regardless of type and size,
28209467b48Spatrick /// functions with aggregates that contain any buffer regardless of type and
28309467b48Spatrick /// size, and functions that contain stack-based variables that have had their
28409467b48Spatrick /// address taken.
RequiresStackProtector()28509467b48Spatrick bool StackProtector::RequiresStackProtector() {
28609467b48Spatrick bool Strong = false;
28709467b48Spatrick bool NeedsProtector = false;
28809467b48Spatrick
28909467b48Spatrick if (F->hasFnAttribute(Attribute::SafeStack))
29009467b48Spatrick return false;
29109467b48Spatrick
29209467b48Spatrick // We are constructing the OptimizationRemarkEmitter on the fly rather than
29309467b48Spatrick // using the analysis pass to avoid building DominatorTree and LoopInfo which
29409467b48Spatrick // are not available this late in the IR pipeline.
29509467b48Spatrick OptimizationRemarkEmitter ORE(F);
29609467b48Spatrick
29709467b48Spatrick if (F->hasFnAttribute(Attribute::StackProtectReq)) {
29809467b48Spatrick ORE.emit([&]() {
29909467b48Spatrick return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
30009467b48Spatrick << "Stack protection applied to function "
30109467b48Spatrick << ore::NV("Function", F)
30209467b48Spatrick << " due to a function attribute or command-line switch";
30309467b48Spatrick });
30409467b48Spatrick NeedsProtector = true;
30509467b48Spatrick Strong = true; // Use the same heuristic as strong to determine SSPLayout
30609467b48Spatrick } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
30709467b48Spatrick Strong = true;
30809467b48Spatrick else if (!F->hasFnAttribute(Attribute::StackProtect))
30909467b48Spatrick return false;
31009467b48Spatrick
31109467b48Spatrick for (const BasicBlock &BB : *F) {
31209467b48Spatrick for (const Instruction &I : BB) {
31309467b48Spatrick if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
31409467b48Spatrick if (AI->isArrayAllocation()) {
31509467b48Spatrick auto RemarkBuilder = [&]() {
31609467b48Spatrick return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
31709467b48Spatrick &I)
31809467b48Spatrick << "Stack protection applied to function "
31909467b48Spatrick << ore::NV("Function", F)
32009467b48Spatrick << " due to a call to alloca or use of a variable length "
32109467b48Spatrick "array";
32209467b48Spatrick };
32309467b48Spatrick if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
32409467b48Spatrick if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
32509467b48Spatrick // A call to alloca with size >= SSPBufferSize requires
32609467b48Spatrick // stack protectors.
32709467b48Spatrick Layout.insert(std::make_pair(AI,
32809467b48Spatrick MachineFrameInfo::SSPLK_LargeArray));
32909467b48Spatrick ORE.emit(RemarkBuilder);
33009467b48Spatrick NeedsProtector = true;
33109467b48Spatrick } else if (Strong) {
33209467b48Spatrick // Require protectors for all alloca calls in strong mode.
33309467b48Spatrick Layout.insert(std::make_pair(AI,
33409467b48Spatrick MachineFrameInfo::SSPLK_SmallArray));
33509467b48Spatrick ORE.emit(RemarkBuilder);
33609467b48Spatrick NeedsProtector = true;
33709467b48Spatrick }
33809467b48Spatrick } else {
33909467b48Spatrick // A call to alloca with a variable size requires protectors.
34009467b48Spatrick Layout.insert(std::make_pair(AI,
34109467b48Spatrick MachineFrameInfo::SSPLK_LargeArray));
34209467b48Spatrick ORE.emit(RemarkBuilder);
34309467b48Spatrick NeedsProtector = true;
34409467b48Spatrick }
34509467b48Spatrick continue;
34609467b48Spatrick }
34709467b48Spatrick
34809467b48Spatrick bool IsLarge = false;
34909467b48Spatrick if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
35009467b48Spatrick Layout.insert(std::make_pair(AI, IsLarge
35109467b48Spatrick ? MachineFrameInfo::SSPLK_LargeArray
35209467b48Spatrick : MachineFrameInfo::SSPLK_SmallArray));
35309467b48Spatrick ORE.emit([&]() {
35409467b48Spatrick return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
35509467b48Spatrick << "Stack protection applied to function "
35609467b48Spatrick << ore::NV("Function", F)
35709467b48Spatrick << " due to a stack allocated buffer or struct containing a "
35809467b48Spatrick "buffer";
35909467b48Spatrick });
36009467b48Spatrick NeedsProtector = true;
36109467b48Spatrick continue;
36209467b48Spatrick }
36309467b48Spatrick
364097a140dSpatrick if (Strong && HasAddressTaken(AI, M->getDataLayout().getTypeAllocSize(
365097a140dSpatrick AI->getAllocatedType()))) {
36609467b48Spatrick ++NumAddrTaken;
36709467b48Spatrick Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
36809467b48Spatrick ORE.emit([&]() {
36909467b48Spatrick return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
37009467b48Spatrick &I)
37109467b48Spatrick << "Stack protection applied to function "
37209467b48Spatrick << ore::NV("Function", F)
37309467b48Spatrick << " due to the address of a local variable being taken";
37409467b48Spatrick });
37509467b48Spatrick NeedsProtector = true;
37609467b48Spatrick }
377097a140dSpatrick // Clear any PHIs that we visited, to make sure we examine all uses of
378097a140dSpatrick // any subsequent allocas that we look at.
379097a140dSpatrick VisitedPHIs.clear();
38009467b48Spatrick }
38109467b48Spatrick }
38209467b48Spatrick }
38309467b48Spatrick
38409467b48Spatrick return NeedsProtector;
38509467b48Spatrick }
38609467b48Spatrick
38709467b48Spatrick /// Create a stack guard loading and populate whether SelectionDAG SSP is
38809467b48Spatrick /// supported.
getStackGuard(const TargetLoweringBase * TLI,Module * M,IRBuilder<> & B,bool * SupportsSelectionDAGSP=nullptr)38909467b48Spatrick static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
39009467b48Spatrick IRBuilder<> &B,
39109467b48Spatrick bool *SupportsSelectionDAGSP = nullptr) {
39273471bf0Spatrick Value *Guard = TLI->getIRStackGuard(B);
39373471bf0Spatrick StringRef GuardMode = M->getStackProtectorGuard();
39473471bf0Spatrick if ((GuardMode == "tls" || GuardMode.empty()) && Guard)
39509467b48Spatrick return B.CreateLoad(B.getInt8PtrTy(), Guard, true, "StackGuard");
39609467b48Spatrick
39709467b48Spatrick // Use SelectionDAG SSP handling, since there isn't an IR guard.
39809467b48Spatrick //
39909467b48Spatrick // This is more or less weird, since we optionally output whether we
40009467b48Spatrick // should perform a SelectionDAG SP here. The reason is that it's strictly
40109467b48Spatrick // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
40209467b48Spatrick // mutating. There is no way to get this bit without mutating the IR, so
40309467b48Spatrick // getting this bit has to happen in this right time.
40409467b48Spatrick //
40509467b48Spatrick // We could have define a new function TLI::supportsSelectionDAGSP(), but that
40609467b48Spatrick // will put more burden on the backends' overriding work, especially when it
40709467b48Spatrick // actually conveys the same information getIRStackGuard() already gives.
40809467b48Spatrick if (SupportsSelectionDAGSP)
40909467b48Spatrick *SupportsSelectionDAGSP = true;
41009467b48Spatrick TLI->insertSSPDeclarations(*M);
41109467b48Spatrick return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
41209467b48Spatrick }
41309467b48Spatrick
41409467b48Spatrick /// Insert code into the entry block that stores the stack guard
41509467b48Spatrick /// variable onto the stack:
41609467b48Spatrick ///
41709467b48Spatrick /// entry:
41809467b48Spatrick /// StackGuardSlot = alloca i8*
41909467b48Spatrick /// StackGuard = <stack guard>
42009467b48Spatrick /// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
42109467b48Spatrick ///
42209467b48Spatrick /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
42309467b48Spatrick /// node.
CreatePrologue(Function * F,Module * M,Instruction * CheckLoc,const TargetLoweringBase * TLI,AllocaInst * & AI)424*d415bd75Srobert static bool CreatePrologue(Function *F, Module *M, Instruction *CheckLoc,
42509467b48Spatrick const TargetLoweringBase *TLI, AllocaInst *&AI) {
42609467b48Spatrick bool SupportsSelectionDAGSP = false;
42709467b48Spatrick IRBuilder<> B(&F->getEntryBlock().front());
428*d415bd75Srobert PointerType *PtrTy = Type::getInt8PtrTy(CheckLoc->getContext());
42909467b48Spatrick AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
43009467b48Spatrick
43109467b48Spatrick Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
43209467b48Spatrick B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
43309467b48Spatrick {GuardSlot, AI});
43409467b48Spatrick return SupportsSelectionDAGSP;
43509467b48Spatrick }
43609467b48Spatrick
43709467b48Spatrick /// InsertStackProtectors - Insert code into the prologue and epilogue of the
43809467b48Spatrick /// function.
43909467b48Spatrick ///
44009467b48Spatrick /// - The prologue code loads and stores the stack guard onto the stack.
44109467b48Spatrick /// - The epilogue checks the value stored in the prologue against the original
44209467b48Spatrick /// value. It calls __stack_chk_fail if they differ.
InsertStackProtectors()44309467b48Spatrick bool StackProtector::InsertStackProtectors() {
44409467b48Spatrick // If the target wants to XOR the frame pointer into the guard value, it's
44509467b48Spatrick // impossible to emit the check in IR, so the target *must* support stack
44609467b48Spatrick // protection in SDAG.
44709467b48Spatrick bool SupportsSelectionDAGSP =
44809467b48Spatrick TLI->useStackGuardXorFP() ||
449*d415bd75Srobert (EnableSelectionDAGSP && !TM->Options.EnableFastISel);
45009467b48Spatrick AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
451*d415bd75Srobert BasicBlock *FailBB = nullptr;
45209467b48Spatrick
453*d415bd75Srobert for (BasicBlock &BB : llvm::make_early_inc_range(*F)) {
454*d415bd75Srobert // This is stack protector auto generated check BB, skip it.
455*d415bd75Srobert if (&BB == FailBB)
456*d415bd75Srobert continue;
457*d415bd75Srobert Instruction *CheckLoc = dyn_cast<ReturnInst>(BB.getTerminator());
458*d415bd75Srobert if (!CheckLoc && !DisableCheckNoReturn)
459*d415bd75Srobert for (auto &Inst : BB)
460*d415bd75Srobert if (auto *CB = dyn_cast<CallBase>(&Inst))
461*d415bd75Srobert // Do stack check before noreturn calls that aren't nounwind (e.g:
462*d415bd75Srobert // __cxa_throw).
463*d415bd75Srobert if (CB->doesNotReturn() && !CB->doesNotThrow()) {
464*d415bd75Srobert CheckLoc = CB;
465*d415bd75Srobert break;
466*d415bd75Srobert }
467*d415bd75Srobert
468*d415bd75Srobert if (!CheckLoc)
46909467b48Spatrick continue;
47009467b48Spatrick
47109467b48Spatrick // Generate prologue instrumentation if not already generated.
47209467b48Spatrick if (!HasPrologue) {
47309467b48Spatrick HasPrologue = true;
474*d415bd75Srobert SupportsSelectionDAGSP &= CreatePrologue(F, M, CheckLoc, TLI, AI);
47509467b48Spatrick }
47609467b48Spatrick
47709467b48Spatrick // SelectionDAG based code generation. Nothing else needs to be done here.
47809467b48Spatrick // The epilogue instrumentation is postponed to SelectionDAG.
47909467b48Spatrick if (SupportsSelectionDAGSP)
48009467b48Spatrick break;
48109467b48Spatrick
48209467b48Spatrick // Find the stack guard slot if the prologue was not created by this pass
48309467b48Spatrick // itself via a previous call to CreatePrologue().
48409467b48Spatrick if (!AI) {
48509467b48Spatrick const CallInst *SPCall = findStackProtectorIntrinsic(*F);
48609467b48Spatrick assert(SPCall && "Call to llvm.stackprotector is missing");
48709467b48Spatrick AI = cast<AllocaInst>(SPCall->getArgOperand(1));
48809467b48Spatrick }
48909467b48Spatrick
49009467b48Spatrick // Set HasIRCheck to true, so that SelectionDAG will not generate its own
49109467b48Spatrick // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
49209467b48Spatrick // instrumentation has already been generated.
49309467b48Spatrick HasIRCheck = true;
49409467b48Spatrick
495*d415bd75Srobert // If we're instrumenting a block with a tail call, the check has to be
49673471bf0Spatrick // inserted before the call rather than between it and the return. The
497*d415bd75Srobert // verifier guarantees that a tail call is either directly before the
49873471bf0Spatrick // return or with a single correct bitcast of the return value in between so
49973471bf0Spatrick // we don't need to worry about many situations here.
500*d415bd75Srobert Instruction *Prev = CheckLoc->getPrevNonDebugInstruction();
501*d415bd75Srobert if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isTailCall())
50273471bf0Spatrick CheckLoc = Prev;
50373471bf0Spatrick else if (Prev) {
50473471bf0Spatrick Prev = Prev->getPrevNonDebugInstruction();
505*d415bd75Srobert if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isTailCall())
50673471bf0Spatrick CheckLoc = Prev;
50773471bf0Spatrick }
50873471bf0Spatrick
50909467b48Spatrick // Generate epilogue instrumentation. The epilogue intrumentation can be
51009467b48Spatrick // function-based or inlined depending on which mechanism the target is
51109467b48Spatrick // providing.
51209467b48Spatrick if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
51309467b48Spatrick // Generate the function-based epilogue instrumentation.
51409467b48Spatrick // The target provides a guard check function, generate a call to it.
51573471bf0Spatrick IRBuilder<> B(CheckLoc);
51609467b48Spatrick LoadInst *Guard = B.CreateLoad(B.getInt8PtrTy(), AI, true, "Guard");
51709467b48Spatrick CallInst *Call = B.CreateCall(GuardCheck, {Guard});
51809467b48Spatrick Call->setAttributes(GuardCheck->getAttributes());
51909467b48Spatrick Call->setCallingConv(GuardCheck->getCallingConv());
52009467b48Spatrick } else {
52109467b48Spatrick // Generate the epilogue with inline instrumentation.
52273471bf0Spatrick // If we do not support SelectionDAG based calls, generate IR level
52373471bf0Spatrick // calls.
52409467b48Spatrick //
52509467b48Spatrick // For each block with a return instruction, convert this:
52609467b48Spatrick //
52709467b48Spatrick // return:
52809467b48Spatrick // ...
52909467b48Spatrick // ret ...
53009467b48Spatrick //
53109467b48Spatrick // into this:
53209467b48Spatrick //
53309467b48Spatrick // return:
53409467b48Spatrick // ...
53509467b48Spatrick // %1 = <stack guard>
53609467b48Spatrick // %2 = load StackGuardSlot
537*d415bd75Srobert // %3 = icmp ne i1 %1, %2
538*d415bd75Srobert // br i1 %3, label %CallStackCheckFailBlk, label %SP_return
53909467b48Spatrick //
54009467b48Spatrick // SP_return:
54109467b48Spatrick // ret ...
54209467b48Spatrick //
54309467b48Spatrick // CallStackCheckFailBlk:
54409467b48Spatrick // call void @__stack_chk_fail()
54509467b48Spatrick // unreachable
54609467b48Spatrick
54709467b48Spatrick // Create the FailBB. We duplicate the BB every time since the MI tail
54809467b48Spatrick // merge pass will merge together all of the various BB into one including
54909467b48Spatrick // fail BB generated by the stack protector pseudo instruction.
550*d415bd75Srobert if (!FailBB)
551*d415bd75Srobert FailBB = CreateFailBB();
55209467b48Spatrick
553*d415bd75Srobert IRBuilder<> B(CheckLoc);
55409467b48Spatrick Value *Guard = getStackGuard(TLI, M, B);
55509467b48Spatrick LoadInst *LI2 = B.CreateLoad(B.getInt8PtrTy(), AI, true);
556*d415bd75Srobert auto *Cmp = cast<ICmpInst>(B.CreateICmpNE(Guard, LI2));
55709467b48Spatrick auto SuccessProb =
55809467b48Spatrick BranchProbabilityInfo::getBranchProbStackProtector(true);
55909467b48Spatrick auto FailureProb =
56009467b48Spatrick BranchProbabilityInfo::getBranchProbStackProtector(false);
56109467b48Spatrick MDNode *Weights = MDBuilder(F->getContext())
562*d415bd75Srobert .createBranchWeights(FailureProb.getNumerator(),
563*d415bd75Srobert SuccessProb.getNumerator());
564*d415bd75Srobert
565*d415bd75Srobert SplitBlockAndInsertIfThen(Cmp, CheckLoc,
566*d415bd75Srobert /*Unreachable=*/false, Weights,
567*d415bd75Srobert DTU ? &*DTU : nullptr,
568*d415bd75Srobert /*LI=*/nullptr, /*ThenBlock=*/FailBB);
569*d415bd75Srobert
570*d415bd75Srobert auto *BI = cast<BranchInst>(Cmp->getParent()->getTerminator());
571*d415bd75Srobert BasicBlock *NewBB = BI->getSuccessor(1);
572*d415bd75Srobert NewBB->setName("SP_return");
573*d415bd75Srobert NewBB->moveAfter(&BB);
574*d415bd75Srobert
575*d415bd75Srobert Cmp->setPredicate(Cmp->getInversePredicate());
576*d415bd75Srobert BI->swapSuccessors();
57709467b48Spatrick }
57809467b48Spatrick }
57909467b48Spatrick
58009467b48Spatrick // Return if we didn't modify any basic blocks. i.e., there are no return
58109467b48Spatrick // statements in the function.
58209467b48Spatrick return HasPrologue;
58309467b48Spatrick }
58409467b48Spatrick
58509467b48Spatrick /// CreateFailBB - Create a basic block to jump to when the stack protector
58609467b48Spatrick /// check fails.
CreateFailBB()58709467b48Spatrick BasicBlock *StackProtector::CreateFailBB() {
58809467b48Spatrick LLVMContext &Context = F->getContext();
58909467b48Spatrick BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
59009467b48Spatrick IRBuilder<> B(FailBB);
59173471bf0Spatrick if (F->getSubprogram())
59273471bf0Spatrick B.SetCurrentDebugLocation(
59373471bf0Spatrick DILocation::get(Context, 0, 0, F->getSubprogram()));
59409467b48Spatrick if (Trip.isOSOpenBSD()) {
59509467b48Spatrick FunctionCallee StackChkFail = M->getOrInsertFunction(
59609467b48Spatrick "__stack_smash_handler", Type::getVoidTy(Context),
59709467b48Spatrick Type::getInt8PtrTy(Context));
59809467b48Spatrick
59909467b48Spatrick B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
60009467b48Spatrick } else {
60109467b48Spatrick FunctionCallee StackChkFail =
60209467b48Spatrick M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
60309467b48Spatrick
60409467b48Spatrick B.CreateCall(StackChkFail, {});
60509467b48Spatrick }
60609467b48Spatrick B.CreateUnreachable();
60709467b48Spatrick return FailBB;
60809467b48Spatrick }
60909467b48Spatrick
shouldEmitSDCheck(const BasicBlock & BB) const61009467b48Spatrick bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
61109467b48Spatrick return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator());
61209467b48Spatrick }
61309467b48Spatrick
copyToMachineFrameInfo(MachineFrameInfo & MFI) const61409467b48Spatrick void StackProtector::copyToMachineFrameInfo(MachineFrameInfo &MFI) const {
61509467b48Spatrick if (Layout.empty())
61609467b48Spatrick return;
61709467b48Spatrick
61809467b48Spatrick for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
61909467b48Spatrick if (MFI.isDeadObjectIndex(I))
62009467b48Spatrick continue;
62109467b48Spatrick
62209467b48Spatrick const AllocaInst *AI = MFI.getObjectAllocation(I);
62309467b48Spatrick if (!AI)
62409467b48Spatrick continue;
62509467b48Spatrick
62609467b48Spatrick SSPLayoutMap::const_iterator LI = Layout.find(AI);
62709467b48Spatrick if (LI == Layout.end())
62809467b48Spatrick continue;
62909467b48Spatrick
63009467b48Spatrick MFI.setObjectSSPLayout(I, LI->second);
63109467b48Spatrick }
63209467b48Spatrick }
633